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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值