nodejs在Windows下c++插件编译
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033
环境:
OS : windows 7 64bit
nodejs : 10.153
node-gyp : 6.0.0
编译器 :vs2017
Python : 2.7.15
1. 安装nodejs
略过
2.安装node-gyp
参考https://www.npmjs.com/package/node-gyp
Windows下:
# 安装
npm install -g node-gyp
查看node-gyp的版本
node-gyp -v
3.安装Python及 Visual Studio
3.1 自动安装
以管理员方式运行cmd,并执行
npm install --global --production windows-build-tools
3.2 手动安装
安装vs2017和python2.7
配置python
npm config set python /path/to/executable/python2.7
配置c++构建工具
npm config set msvs_version 2017
4.编写测试代码
4.1 编写hello.cc
#include <node.h>
#include <v8.h>
using namespace v8;
void Method(const v8::FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void Init(Handle<Object> exports)
{
Isolate* isolate = Isolate::GetCurrent();
exports->Set(String::NewFromUtf8(isolate, "hello"),
FunctionTemplate::New(isolate, Method)->GetFunction());
}
NODE_MODULE(hello, Init)
注意,所有的 Node.js 插件必须导出一个如下模式的初始化函数:
void Initialize(Local<Object> exports);
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
NODE_MODULE 后面没有分号,因为它不是一个函数(详见 node.h)。
module_name 必须匹配最终的二进制文件名(不包括 .node 后缀)。
在 hello.cc 示例中,初始化函数是 Init,插件模块名是 addon。
4.2 编写构建文件binding.gyp
{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ]
}
]
}
4.3 编译.node模块
node-gyp configure --debug build
–debug参数表示生成debug文件
4.4 编写hello.js
//hello.js
var addon = require('./build/Debug/hello.node');
console.log(addon.hello()); // 'world'
require的路径需要和3.3中编译出来的路径一致
4.5 运行
node hello.js
4.6 结果
$ node hello.js
world
觉得文章对你有帮助,可以扫描二维码捐赠给博主,谢谢!
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033
License
License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎
Reference:
1.http://nodejs.cn/api/addons.html
2.https://www.jianshu.com/p/8a9f4304557c
3.https://www.npmjs.com/package/node-gyp
4.https://github.com/felixrieseberg/windows-build-tools