1.环境
Ubuntu 14.04
node 4.5.0
node-gyp 3.4.0
2.项目
新建项目,在项目文件的node_modules中加入组件nan和bindings;或者在package.json的dependencies中加入这两个组件,用nmp安装
3.c++源码
#include <nan.h>
void Method(const Nan::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(Nan::New("world").ToLocalChecked());
}
void Init(v8::Local<v8::Object> exports) {
exports->Set(Nan::New("hello").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(Method)->GetFunction());
}
NODE_MODULE(hello, Init)
4.binding.gyp
{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ],
"include_dirs": [
"<!(node -e \"require('nan')\")"
]
}
]
}
5.js源码
var addon = require('bindings')('hello');
console.log(addon.hello()); // 'world'
6.
编译addon
node-gyp configure build
7.执行
node hello.js