a blog for those who code

Wednesday, 21 October 2015

Write .Net and Node.js code together using Edge.js

In this post we will be discussing about writing .Net and Node.js code together using Edge.js. Using Edge.js you connect Node.js and .Net on Windows, MacOS, and Linux. There are a lot of situations which will benefit you from a combination of Node.js and .Net like you have existing .Net components and you want that to be used in Node.js application.


Simple Example

var edge = require('edge');

var edgeExample = edge.func(function() {/*
  async(input) => {
    return "Hello World using " + input.ToString();
  }
*/});

edgeExample('Edge', function (error, result) {
  if(error) throw error;
    console.log(result);
});

In the above code we have written C# script into a Node.js application using edge.func(). As you can see we are passing value "Edge" from the Node.js to the C# script and C# script is returning the string "Hello World using Edge" back to Node.js. Edge takes care of marshaling data between CLR and V8. You can use pre-compiled CLR code (dlls) or can write source code directly into the Node.js application. One thing to note that it supports all the platforms i.e. Windows, Mac and Linux.

Like a Console Application in C# where you need to have a static main method, Edge needs a Class Startup and this class must invoke method that matches the Func<object, Task<object>> delegate signature as shown below.

var edge = require('edge');

var edgeExample = edge.func(function() {/*
  using System.Threading.Tasks;

  public class Startup
  {
    public async Task<object> Invoke(object input)
    {
      return ((int)input * 2);
    }
  }
*/});

edgeExample(10, function (error, result) {
  if(error) throw error;
    console.log(result);
});

In the above code we have taken a integer input and doubled its value. One thing to note that the input goes as an object and not string or integer, so you need to convert it before using otherwise you will get an error like below -


For more examples, Check : https://github.com/tjanczuk/edge.

Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

1 comment:

  1. Really cool to see .Net and Node.js joining forces on many levels.

    ReplyDelete