Home  >  Article  >  php教程  >  Use C++ to write extension modules for node.js

Use C++ to write extension modules for node.js

高洛峰
高洛峰Original
2016-12-26 09:42:491158browse

Prerequisite: Install node.js, Python2.7 and visual studio 2013.

Process:
First install the GYP project generation tool, npm install -g node-gyp.
Create the test directory, which is our working directory. Create a src directory under this directory to store the C++ source code. Create a new text file named binding.gyp. This is the gyp project file. The content is as follows:

{
    'targets':[{
        'target_name':'hello',
        'sources':['src/hello.cc']
    }]
}

Write a simple hello.cc with the following content:

#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 ----build will appear, under which vs2013 is generated for you Project file, so that it can be edited and compiled in vs2013.
Of course, you can also directly use the command node-gyp build to compile.

The test js program is as follows:

var hello = require(&#39;./hello&#39;);
console.log(hello.hello());

Some problems were encountered and the records are as follows:

1. C:UsersAdministrator.node-gyp

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn