Asp.net core node services to execute your nodejs scripts

Nowadays, it is very common to have pieces of code developed in different languages and technologies, and today, more than ever in Javascript.

If you have a tested and battle proven javascript module, maybe you don’t want to rewrite it from scratch in C# to use it in asp.net, and you prefer to invoke it and fetch the results.

This post will show how to use Microsoft Asp Net Core Node Services in asp.net to execute our javascript commonjs modules.

In the following example, we will consume an online free json post service, that returns lorem ipsum posts information based on the request page id. To Achieve this we have a really simple nodejs module that will fetch the contents from the api using the library axios.

We are going to fetch this information through the Post Api Controller and return them in Json to the client.

Lets get started:

 

First of all we create a new asp.net core project:

create_aspnetcore_project

 

Then we add the Reference to Microsoft.AspNetCore.NodeServices in  project.json file:

 

add_nodeservices_package

 

To finish the setup, we have to create a npm configuration file and add the axios reference that will be used by our node script:

To add the npm configuration file use Add > new Item > client-side > npm configuration file and then add the axios dependency as the following image:

 

npm_axios_package_install

 

With this the setup is complete, let’s jump to the api configuration, we want to add Node Services and fast configure the JsonSerializer indentation settings on our Startup.cs class in ConfigureServices method:

 

Once our api is configured to use Node Services we are going to create the Post Controller, and inject the node services in the constructor. The framework will automatically provide it to us so no further configuration is needed. We want to serialize the output to be an ExpandoObject so we can dynamically access to the properties in case it is needed. Right now we just want to send the output to the client in Json format.

The next step will be creating a folder called Node in our root folder and add the following nodejs script within a file named postClient.js.

This js module will just create a GET request to the api, requesting the post Id and invoking the callback based on the network request result:

 

NOTE: We should define a callback in the module parameters so Node Services can play the output results.
If we want the script to be successful we should pass a null error callback. On the other hand we will provide an error as the first callback parameter so the nodeService.InvokeAsync throws an Exception.

 

Final Steps, executing the controller action:

Everything is in place and we are going to use Fiddler to create requests to the post controller requesting different page ids:

 

fiddler_compose_request

 

Once we execute the request we can see debugging the resulting output from the js script:

 

debugging_post_controller

 

And then we get the output on fiddler as well:

 

fiddler_response

 

And that’s all for today, I hope you enjoyed.

Happy Coding!.

geeks.ms node notifier (no te pierdas ningún post) (node & js ES6)

Ayer por la tarde llovía y decidí entrar a ver las nuevas entradas en los blogs de Geeks, y me di cuenta de que no siempre me acuerdo o tengo el tiempo de hacerlo asiduamente, así que tenía ganas de tirar algo de código y me puse manos a la obra.

El proyecto consiste en una aplicación node utilizando js (ES6). El script se conecta al blog de geeks, y parsea las entradas de los últimos posts añadidos, avisándonos mediante un popup en el escritorio de los nuevos posts que van llegando mientras esta corriendo el demonio.

 

Geeks.ms node notifier

 

El proyecto utiliza los siguientes módulos de node:

axios (Http client basado en promesas que funciona en browser y en node)

cheerio (Implementación de Jquery para trabajar del lado del servidor)

eventEmitter (Modulo para subscribirse y publicar eventos)

fs (Módulo de node para acceder al sistema de archivos)

node-notifier (Notificaciones de escritorio compatibles con todos los SO’s)

Los parámetros como el store path, fichero temporal y el intervalo de crawling (milisegundos) a la web es configurable en el fichero config/appConfig.

Para instalar el proyecto tenemos que instalar los paquetes con npm e instalar forever. El paquete forever nos permite lanzar nuestro script de node como daemon, y se encarga de gestionarlo ante posibles fallos o salidas inexperadas.

Ejecutamos en la consola:

npm install

npm install forever -g

forever start boot.js

Una vez forever lanza el script lo dejar corriendo en background, y tan solo tenemos que utilizar el comando forever list para listar los demonios que tenemos corriendo actualmente. La salida del comando nos mostrará el uptime del proceso, y el log donde está volcando los eventos y console.log que se van registrando.

foreverlist

 

Y eso es todo!. Espero que los que os decidáis a instalarlo os sea útil.

El repositorio de github lo podéis encontrar en el siguiente enlance:

https://github.com/CarlosLanderas/GeekMs-Node-Notifier

Edit: Parece que funciona 🙂

notifier