系统环境ubuntu18.04
一、首先安装node
以上是各个版本下的安装链接
1、
Node.js v8.x:
# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_8.x | bash -
apt-get install -y nodejs
检验:node -v
注意:如果是ubuntu12.04的,安装nodejs会出现各种问题,建议升级版本
二、安装node-gyp
https://github.com/nodejs/node-gyp#installation
1、npm install -g node-gyp
2、node-gyp --python /path/to/python2.7
三、下面就是插件开发的步骤
实例 Hello World
1、
首先,创建 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(NODE_GYP_MODULE_NAME, init)
} // namespace demo
2、
当源代码已被编写,它必须被编译成二进制 addon.node
文件。 要做到这点,需在项目的顶层创建一个名为 binding.gyp
的文件,它使用一个类似 JSON 的格式来描述模块的构建配置。 该文件会被 node-gyp(一个用于编译 Node.js 插件的工具)使用。
{
"targets": [
{
"target_name": "addon",
"sources": [ "hello.cc" ]
}
]
}
3、测试
当构建完成时,二进制插件就可以在 Node.js 中被使用,通过 require()
构建后的 addon.node
模块:
// hello.js
const addon = require('./build/Release/addon');
console.log(addon.hello());
// 打印: 'world'
构建addon模块步骤
(1)node-gyp configure --debug
(2)node-gyp build
就会在build/Debug/下面生成一个addon.node
然后执行,node hello.js执行结果如下 world
表示该模块成功生成
最后不能忘记环境变量
$ export npm_config_devdir=/tmp/.gyp