简介
本编文章编写与2019年3月,一直在个人笔记中未发布,以下部分技术可能已过时,可参考思路和步骤。本文详细介绍了nodejs依赖node-gyp使用c/c++的使用步骤。
安装和配置基础依赖
-
安装Python2.7
安装python2.7,仅支持2.7.X,暂时不支持3.X
新建项目
npm init
- 安装node-gyp
npm install nan@latest --save
node-gyp支持nodejs编译c/c++代码的模块
npm install node-gyp -g
- src下新建
hello.cc
// hello.cc
#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(addon, init)
}
- 项目根目录新增文件
binding.gyp
# binding.gyp
{
'targets': [
{
'target_name': 'addon',
'sources': [
'src/hello.cc'
],
'dependencies': [
]
}
]
}
- 执行编译命令
node-gyp configure build
一切顺利的话,在hello文件夹下会出现build文件夹,在build/Release下有三个名为addon的文件。实际上我们需要用到的是后缀为.node的文件。下面写一个测试js吧。
test.js内容很简单,只需要像引用其他的node模块一样require我们自己写的插件。
var addon = require('./build/Release/addon.node');
console.log(addon.hello());
node test.js