admin管理员组

文章数量:1426123

Our main backend server is a 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 acplish this or am I best of running a separate node server for this functionality?

Our main backend server is a 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 acplish this or am I best of running a separate node server for this functionality?

Share Improve this question edited Jan 22, 2022 at 2:07 Yilmaz 50.1k19 gold badges218 silver badges271 bronze badges asked Jan 19, 2022 at 5:44 MattMatt 2,86311 gold badges58 silver badges102 bronze badges 1
  • Just for curious read , here is an interesting article khalidabuhakmeh./… – GSM Commented Jan 28, 2022 at 7:23
Add a ment  | 

1 Answer 1

Reset to default 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 plete 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.

本文标签: cIntegrating node modules and JavaScript into our Web API controller callsStack Overflow