Skip to content
Open core software, built in Singapore Established 2018  /  Five utilities
Jering
Talk to us

Quick Start

Javascript.NodeJS Jering documentation Open source NuGet package
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

Package Manager
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.

C#
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.

C#
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.

C#
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.

Reference shelf