首先介绍使用v8 API跟使用swig框架的不同:
(1)v8 API方式为官方提供的原生方法,功能强大而完善,缺点是需要熟悉v8 API,编写起来比较麻烦,是js强相关的,不容易支持其它脚本语言。
(2)swig为第三方支持,一个强大的组件开发工具,支持为python、lua、js等多种常见脚本语言生成C++组件包装代码,swig使用者只需要编写C++代码和swig配置文件即可开发各种脚本语言的C++组件,不需要了解各种脚本语言的组件开发框架,缺点是不支持javascript的回调,文档和demo代码不完善,使用者不多。
一、纯JS实现Node.js组件
(1)到helloworld目录下执行npm init 初始化package.json,各种选项先不管,默认即可。
(2)组件的实现index.js,例如:
module.exports.Hello = function(name) { console.log('Hello ' + name);}
(3)在外层目录执行:npm install ./helloworld,helloworld于是安装到了node_modules目录中。
(4)编写组件使用代码:
var m = require('helloworld');m.Hello('zhangsan');//输出: Hello zhangsan
二、 使用v8 API实现JS组件——同步模式
(1)编写binding.gyp, eg:
{ "targets": [ { "target_name": "hello", "sources": [ "hello.cpp" ] } ]}
(2)编写组件的实现hello.cpp,eg:
#include <node.h>namespace cpphello { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void Foo(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World")); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "foo", Foo); } NODE_MODULE(cpphello, Init)}
(3)编译组件
node-gyp configurenode-gyp build./build/Release/目录下会生成hello.node模块。
(4)编写测试js代码
const m = require('./build/Release/hello')console.log(m.foo()); //输出 Hello World
(5)增加package.json 用于安装 eg:
{ "name": "hello", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "node test.js" }, "author": "", "license": "ISC"}
(5)安装组件到node_modules
进入到组件目录的上级目录,执行:npm install ./helloc //注:helloc为组件目录
会在当前目录下的node_modules目录下安装hello模块,测试代码这样子写:
var m = require('hello');console.log(m.foo());
三、 使用v8 API实现JS组件——异步模式
新闻热点
疑难解答
图片精选