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 MyFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { info.GetReturnValue().Set(Nan::New("hello world").ToLocalChecked());}void CreateFunction(const Nan::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::FunctionTemplate> tp1 = Nan::New<v8::FunctionTemplate>(MyFunction); v8::Local<v8::Function> fn = tp1->GetFunction(); fn->SetName(Nan::New("theFunction").ToLocalChecked()); info.GetReturnValue().Set(fn);}void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) { Nan::SetMethod(module, "exports", CreateFunction);}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');var fn = addon();console.log(fn());6.编译addoncd到源码目录下
node-gyp configure build 7.执行cd 到源码目录下
node hello.js
新闻热点
疑难解答
图片精选