How to Create a Addon in Nodejs

21 / Dec / 2016 by Mayank Tyagi 2 comments

Writing your backend API in server side JavaScript is great, and we always do such kind of work using some predefined built-in library but if you want to use a function which is not feasible to use in Node.js or no module is available for that in node package manager but it is available in C/C++ libraries. So addons will help us to use that C/C++ library in Node.js, like a node module.

Let’s relate this to a real situation, suppose I want to find the cursor position on my desktop using Node.js  and we know how to interact with the system we need to write the code in C/C++ , in this case, we have to write our code in C/C++ and use it in our Nodejs code.

Start to create my first addon in node

Before we start we must have some idea about some terminologies, so let’s have a brief look on these terminologies:-

Node-gyp :- node-gyp is a cross-platform command line tool written in Node.js for compiling native addon modules for Node.js. It bundles the gyp project used by chromium team and takes away the pain of dealing with the differences in build platform.

NAN :- A header file filled with macro and utility goodness for making add-on development for Node.js or we can say an abstraction layer between the C++ code and the Node.

Let’s try to make a very simple Addon:-

  • Create your project and run npm init in your root directory to create your package.json.
  • Now we need nan that we have discussed earlier. NAN will serve as a thin abstraction layer between the c++ code we write. Command to install nan 
    •  npm install nan@latest –save

  • Add a “gypfile”: True (which is optional) entry to your package.json so that npm knows that this is a binary addon that needs compiling and invoke node-gyp. When node-gyp is invoked , it will look for a binding.gyp file.
  • Create “binding.gyp”file :-
    {
      "targets": [
        {
          "target_name": "myAddon", 
          "sources": [ "myAddon.cc" ],
          "include_dirs": [
            "<!(node -e \"require('nan')\")"
          ]
        }
      ]
    }
    

     

    This file tells GYP the following things:

    target name :- binary output target is called “myAddon” ,would be used with “myAddon.node” file would exist either at path ./build/Release/ or ./build/Debug/ depending on the invocation of node-gyp.

    source:- the source file to compile can be one or multiple.

    include_dirs :- when compiling the directory containing the NAN needs to be used as an “include”, it means compile with -lpath/to/NAN.

  • Create a file myAddon.cc with the following content
#include <nan.h>
using v8::FunctionCallbackInfo;
   using v8::Isolate;
   using v8::Object;
   using v8::String;
   using v8::Value;
   using v8::Handle;

   /**
    *simple function to be export from this c++ code
   **/
 void sayHelloWorld(const FunctionCallbackInfo<Value>& args){
    Isolate* isolate = args.GetIsolate();
       args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World !!!!!!!!!!!"));
   }

/*entry point,we can recieve upto two arguments here.First is export like  module.export
*/
void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "sayHelloWorld", sayHelloWorld);//NODE_SET_MET  HOD to export
}

//to define entry point,first argument must match with target name in binding.gyp
NODE_MODULE(myAddon, Init)

  • Install node-gyp using  “npm install -g node-gyp” command.
  • Compile your addon with the command “node-gyp build”.
  • Create your root file with name index.js
	var addon = require('./build/Release/myAddon.node');
	
	console.log(addon.sayHelloWorld());

Now up to this step we successfully created our main/root file which is requiring our nodejs addon. After this, you have the freedom to use all the functionality exposed in your own addon. In our example, we have called ‘sayHelloWorld’ function which is created inside our nodejs addon. You can resolve any problem by creating the function based on your use case. After this execute your main/root file using the following command:

  • Run “node index.js”.

Hope this will help you to create your own addon. 🙂

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply to Mayank Cancel reply

Your email address will not be published. Required fields are marked *