Integrating node modules and JavaScript into our Web API controller calls

Solution 1:

Option 1. Access A Node.js Server Script From C#/.Net 5

Jering.Javascript.NodeJS enables you to invoke javascript in a Node.js module from C#. With this ability, you can use Node.js scripts/modules from within your C# projects. Supports: Callbacks, Promises and Async/Await. Get js scripts via file path, string or stream. You can run a single global instance of your Node.js App that remains in memory or create a new instance for each call. See an example on Invoking Javascript From File.

Install Via Package Manager or .Net CLI

Install-Package Jering.Javascript.NodeJS
#or
dotnet add package Jering.Javascript.NodeJS

some-module.js

module.exports = {
    doSomething: (callback, message) => callback(null, { message: message + '!' }),
    doSomethingElse: (callback, message) => callback(null, { message: message + '.' })
}

In your .Net App

var services = new ServiceCollection();
services.AddNodeJS();
ServiceProvider serviceProvider = services.BuildServiceProvider();
INodeJSService nodeJSService = serviceProvider.GetRequiredService<INodeJSService>();

public class Result {
  public string? Message { get; set; }
}
Result? result = await nodeJSService.InvokeFromFileAsync<Result>("some-module.js", "doSomething", args: new[] { "success" });
Assert.Equal("success!", result?.Message);

This is a basic implementation example. You should see the Jering.Javascript.NodeJS Docs for complete examples of installation, configuration and usage.


Option 2. HTTP REST / Web Socket

Create an HTTP Rest or WebSocket Wrapper around your JS scripts and call them from the .Net App. In your .Net App, use HttpClient class to make HTTP requests. Then over in Node.js wrap your scripts with routes to access various methods. Something like:

const express = require('express');
const app = express();
const port = 3000;

app.get('/some/endpoint', (req, res) => {
  // Gets executed when the URL http://localhost:3000/some/endpoint
  // Do your thing here 
  // Return it back to .Net with:
  res.send(JSON.stringify({some_response: "Hello There"}))
});

// Start the http server
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
});

Using the HTTP Rest/WebSocket option will require that you already have your node.js app running (and keep it running) before you attempt to call the endpoints from .Net.


Option 3. Execute Standard Javascript Embedded Scripts

Here are the most popular .Net modules that will allow you to run Standard Javascript code within your C# .Net Service. However, these both execute your JS Scripts using the V8 Engine and will not work for Node.js specific methods such as FileSystem. These will also not allow the use of require() or Import. This might be a good option if you have very limited Javascript needs and will not be adding additional JS functions in the future.

  1. Microsoft.ClearScript
  2. Jint
  3. Javascript.Net

This option is quick and simple for very small scripts, but would be the most difficult to update and maintain your JS scripts.