Write the extension module for node.js using C++
- 2020-06-01 08:16:59
- OfStack
Prerequisite: install node.js, Python2.7 and visual studio 2013.
Process:
First, install the GYP project generation tool, npm install-g node-gyp.
Create test directory, which is our working directory. Under this directory, create another src directory to store C++ source code. Create a new text file named binding.gyp, which is the project file of gyp.
{
'targets':[{
'target_name':'hello',
'sources':['src/hello.cc']
}]
}
Write another simple hello.cc, which reads as follows:
#include <node.h>
using namespace v8;
Handle<Value> Hello(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("Hello world!"));
}
void init(Handle<Object> target) {
NODE_SET_METHOD(target, "hello", Hello);
}
NODE_MODULE(hello, init)
Then run the command: node-gyp configure
If run correctly, a directory will appear, build, which generates the vs2013 project files for you, so that you can edit and compile in vs2013.
You can also compile directly with the command node-gyp build.
Test the js procedure as follows:
var hello = require('./hello');
console.log(hello.hello());
Some problems were encountered, which were recorded as follows:
1, C:\Users\ Administrator.node-gyp \0.10.33 there is no default Debug directory in this directory. When compiled into debug file in vs2013, error LNK1104 will be prompted: cannot open file 'C:\Users\ Administrator.node-gyp \0.10.33\Debug\ node.lib ', create an Debug directory and copy node.lib from the same directory as your operating system environment.
2. NODE_MODULE(hello, init) hello is the module name, which needs to be 1 with the file name, otherwise it will compile well and run incorrectly. Because when you're on require('./ hello.node '), you're looking for both the appropriate file and the corresponding MODULE.
3. I refer to the book node.js by park ling, and study it with reference to some web pages. In the gyp project file provided by the book, there is one item of conditions, 'libraries' : [' -lnode.lib '], because of this sentence, the error is reported at compile time 1: can't open node. lib, obviously the file exists, but I found a lot of error, and did not solve it. Later, I directly copied node. lib to the working directory, and successfully compiled it with the command line! However, in vs2013, the error is still the same, I can't think right, finally on the official website, found that the examples of others do not give this parameter, I tried to delete this thing, the result is 1 cut OK! Who can give a correct explanation, gods? !
That's the end of this article, I hope you enjoy it.