Quick Start
Documentation menu
This guide installs Jering.Javascript.NodeJS, registers the service and invokes a small JavaScript module from C#.
Before you start
Install Node.js and confirm that node --version works in the terminal where your application will run. The library finds the Node.js executable through the PATH environment variable.
Install
dotnet add package Jering.Javascript.NodeJS
Register the service
For a dependency injection setup, add the service to the collection and resolve INodeJSService. The registration is a singleton, so the same Node.js process is reused.
var services = new ServiceCollection();
services.AddNodeJS();
var provider = services.BuildServiceProvider();
var node = provider.GetRequiredService<INodeJSService>();
Invoke JavaScript
This example passes a module as a string. The module exports a function that receives a callback and an argument, then returns an object.
var result = await node.InvokeFromStringAsync<Greeting>(
"module.exports = (callback, name) => callback(null, { text: 'Hello ' + name })",
args: new object[] { "Jering" });
public class Greeting
{
public string Text { get; set; }
}
Invoke from a file
For a module that lives on disk, use InvokeFromFileAsync. The path is relative to the working directory of the host process.
var result = await node.InvokeFromFileAsync<Greeting>("exampleModule.js", args: new object[] { "Jering" });
Clean up
The Node.js process exits when its parent process dies. If you need to stop it earlier, call Dispose() on the service. After disposal, invocation methods throw ObjectDisposedException.
Next
Read Advanced for options, concurrency and debugging.