How to Create a Addon in Nodejs

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.

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.

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: