C++编写Node.js插件(Addon)

     Google V8引擎的性能无用质疑,不过相对C/C++而言,还是有差距的,毕竟JavaScript是脚本语言。对于性能要求苛刻的可以考虑C++编写,本文介绍如何使用C++编写Node.js插件。

     第一步、编写C++代码

 1 // hello.cc
 2 #include <node.h>
 3 
 4 namespace demo {
 5 
 6 using v8::FunctionCallbackInfo;
 7 using v8::Isolate;
 8 using v8::Local;
 9 using v8::Object;
10 using v8::String;
11 using v8::Value;
12 
13 void Method(const FunctionCallbackInfo<Value>& args) {
14   Isolate* isolate = args.GetIsolate();
15   args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
16 }
17 
18 void init(Local<Object> exports) {
19   NODE_SET_METHOD(exports, "hello", Method);
20 }
21 
22 NODE_MODULE(addon, init)
23 
24 }  // namespace demo

     第二部、编写构建脚本building.gyp文件

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

     第三部、编写package.json

     可以通过npm init模板生成。

{
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "test.js",
  "dependencies": {},
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "install": "node-gyp rebuild"
  },
  "author": "",
  "license": "ISC",
  "gypfile": true
}

     第四部、安装

     npm install

     系统需要安装python工具,下载地址:https://www.python.org/downloads/release/python-2712/

     

     第五步、测试运行

// hello.js
const addon = require('./build/Release/addon');

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

     

     完整代码参考:https://git.oschina.net/zhujf21st/node-cc.git

posted @ 2016-08-15 15:37  jeffrey.chu  阅读(4897)  评论(8编辑  收藏  举报

99code棋牌网