1.環境
Ubuntu 14.04
node 4.5.0
node-gyp 3.4.0
2.項目
新建項目,加入組件nan和bindings
方法一、在項目文件的node_modules中復制組件nan和bindings的全部代碼包;
方法二、在package.json的dependencies中加入這兩個組件,用nmp安裝
3.c++源碼
//addon.cc#include <nan.h>void Add(const Nan::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() < 2) { Nan::ThrowTypeError("Wrong number of arguments"); return; } if (!info[0]->IsNumber() || !info[1]->IsNumber()) { Nan::ThrowTypeError("Wrong arguments"); return; } double arg0 = info[0]->NumberValue(); double arg1 = info[1]->NumberValue(); v8::Local<v8::Number> num = Nan::New(arg0 + arg1); info.GetReturnValue().Set(num);}void Init(v8::Local<v8::Object> exports) { exports->Set(Nan::New("add").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(Add)->GetFunction());}NODE_MODULE(addon, Init)4.binding.gyp{ "targets": [ { "target_name": "addon", "sources": [ "addon.cc" ], "include_dirs": [ "<!(node -e /"require('nan')/")" ] } ]}5.js源碼//addon.jsvar addon = require('bindings')('addon.node')console.log('This should be eight:', addon.add(3, 5))6.編譯addoncd到源碼目錄下
node-gyp configure build 7.執行cd 到源碼目錄下
node hello.js
新聞熱點
疑難解答
圖片精選