nodejs在Linux下c++插件运行

245 阅读1分钟

nodejs在Linux下c++插件运行


如需转载请标明出处
QQ技术交流群:129518033

### 文章目录* nodejs在Linux下c++插件运行

环境:

Linux : ubuntu 16.04

nodejs : 10.15.2

node-gyp : 5.0.3

GCC : 5.4.0

Python : 2.7

1. 安装nodejs

略过

参考:nodejs在Linux下的安装

2.安装node-gyp

参考https://www.npmjs.com/package/node-gyp

Linux下:

前提:

  • python (推荐 v2.7, v3.x.x 暂未支持)
  • make
  • C/C++编译工具,例如GCC
# 安装
npm install -g node-gyp

建立软连接(这里假设nodejs安装路径为/app/software/)

sudo ln -s /app/software/nodejs/bin/node-gyp /usr/local/bin/ 

查看node-gyp的版本

node-gyp -v

3.编写测试代码

3.1 编写hello.cc

#include <node.h>
#include <v8.h>

using namespace v8;

void Method(const v8::FunctionCallbackInfo<Value>& args) 
{
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void Init(Handle<Object> exports) 
{
  Isolate* isolate = Isolate::GetCurrent();
  exports->Set(String::NewFromUtf8(isolate, "hello"),
      FunctionTemplate::New(isolate, Method)->GetFunction());

}

NODE_MODULE(hello, Init)

注意,所有的 Node.js 插件必须导出一个如下模式的初始化函数:

void Initialize(Local<Object> exports);
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

NODE_MODULE 后面没有分号,因为它不是一个函数(详见 node.h)。

module_name 必须匹配最终的二进制文件名(不包括 .node 后缀)。

hello.cc 示例中,初始化函数是 Init,插件模块名是 addon。

3.2 编写构建文件binding.gyp

{
  "targets": [
    {
      "target_name": "hello",
      "sources": [ "hello.cc" ]
    }
  ]
}

3.3 编译.node模块

node-gyp configure --debug build

–debug参数表示生成debug文件

3.4 编写hello.js

//hello.js

var addon = require('./build/Debug/hello.node');

console.log(addon.hello()); // 'world'

require的路径需要和3.3中编译出来的路径一致

3.5 运行

node hello.js

3.6 结果

$ node hello.js 
world

License

License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎


Reference:
1.nodejs.cn/api/addons.…
2.www.jianshu.com/p/8a9f43045…
3.www.npmjs.com/package/nod…