Using Node Services In ASP.NET Core

This post is about running Javascript code in the Server. Because a huge number of useful, high-quality Web-related open source packages are in the form of Node Package Manager (NPM) modules. NPM is the largest repository of open-source software packages in the world, and the Microsoft.AspNetCore.NodeServices package means that you can use any of them in your ASP.NET Core application.

To use Node Services, first you need to include the reference of Microsoft.AspNetCore.NodeServices package in your project file. You can do this using dotnet add package Microsoft.AspNetCore.NodeServices command.
  1. <ItemGroup>  
  2.     <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0-preview1-final" />  
  3.     <PackageReference Include="Microsoft.AspNetCore.NodeServices" Version="1.1.1" />  
  4. </ItemGroup>  
Then you need to add the Node Services middleware to the request pipeline. You can do it in your ConfigureServices() method.
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddMvc();  
  3.     services.AddNodeServices();  
  4. }  
Now you’re able to get instance of INodeServices in your application. INodeServices is the API through which .NET code can make calls into JavaScript that runs in a Node environment. You can use FromServices attribute to get the instance of `INodeServices’ in your action method. Here is Add method implementation in MVC.
  1. public async Task < IActionResult > Add([FromServices] INodeServices nodeServices) {  
  2.     var num1 = 10;  
  3.     var num2 = 20;  
  4.     var result = await nodeServices.InvokeAsync < int > ("AddModule.js", num1, num2);  
  5.     ViewData["ResultFromNode"] = $ "Result of {num1} + {num2} is {result}";  
  6.     return View();  
  7. }  
And here is the code of AddModule.js file.
  1. module.exports = function(callback, num1, num2) {  
  2.     var result = num1 + num2;  
  3.     callback(null, result);  
  4. };  
You need to use the type of the result in your InvokeAsync method, in this example I am using int. NodeServices allows ASP.NET Core developers to make use of the entire NPM ecosystem, which gives rise to a huge range of possibilities. You can find the full source code on GitHub.

Happy Programming.