Part one: babby’s first native module
This is the first part in what will hopefully be a multipart tutorial as I write a native module for imagemagick. Today, we will take a look at making the most basic of of native modules and how to use it with Node.
To start off, lets create a file called
testModule.cpp. This is where everything (for now) will happen. Heres what we need to start:
Note, this is assuming you have NodeJS installed already and in your path (if you dont, go do that!). We need to import both the Node header and the V8 header.
To build our module, we will be using the
node-waf tool that comes bundled with NodeJS. In the same directory as
testModule.cpp create a file called
wscript and put the following stuff in it:
The wscript file sets up needed environment variables and libraries that need to be linked at compile time. Think of it as some kind of makefile. The
t.target property needs to match up to the name of the export property in your module (I’ll point this out when we get there).
Now, to build your module simply run the following:
Alright, now that we have those basics out of the way, lets make a module that when called, returns the string “Hello World”.
So to quote the V8 handbook:
A handle is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
A scope can be thought of as a container for any number of handles. When you’ve finished with your handles, instead of deleting each one individually you can simply delete their scope.
So now that we have a function that can do some kind of work, how do we expose it to Node? Lets take a look:
Now, a note on the
NODE_MODULE(…) line. Before when I said
t.target needed to match, this is where it needs to. The first argument of
NODE_MODULE needs to be the same as your target value.
Once you have all of that, build your new node module. To try it out, run node and import your module.
That’s it! You now have your first native module. In my next post, we’ll dig deeper into building something a bit more substantial. One of the main draws of NodeJS is its asynchronous nature, so next time we’ll take a look at how to go about building a module with asynchronous function using libuv that its at the very core of NodeJS.