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'