1

Our main backend server is a .net 5 web API project. I'm needing to integrate some javascript modules and javascript code into our functionality. I'm wanting to save on the time of rewriting these modules all into c# to access from our code. Are there any packages or methods to accomplish this or am I best of running a separate node server for this functionality?

1
  • Just for curious read , here is an interesting article khalidabuhakmeh.com/… Commented Jan 28, 2022 at 7:23

1 Answer 1

8
+150

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.