1.
题话
前些日子面试了node的实习工作,不出意外明天就要去上班了,可以说大学算是画上了句号(即使还有一年才毕业哈哈),原本是要找spark和hadoop的,可惜招实习的基本没有,要么离学校太远,要么全职的要求太高,而我只是想找个实习的.希望有机会转吧
2.
使用C++扩展库需要知道些组件和API
(1).V8 库 它提供了js的实现,如创建对象,调用函数
(2).libuv 实现node的事件循环,承担线程任务,同时提供一些跨平台简化系统任务的库,如 filesystem, sockets, timers and system events
(3).node内部库 主要供C++拓展的时候使用,例如node::ObjectWrap
(4).静态链接库 这个可根据依赖加载,放在deps/ 默认情况下V8和openssl是默认导出的
3.
使用NODE_MODULE(addon, init) ## 注册模块,这句代码是些hello的要点,毕竟我们写node的拓展库,肯定要告诉系统你可以暴露什么给上层的调用对吧
接着
#include <node.h>
namespace demo{
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void myMethod(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void init(Local<Object> exports){
NODE_SET_METHOD(exports,"hello",myMethod);
}
NODE_MODULE(addon, init)
} //namespace demo
作不同语言的交互肯定不能直接call,需要暴露某种数据结构来告诉双方(理解为双方的协议)
配置文件binding.gyp,方便node-gyp configure命令生成makefile
{
"targets": [
{
"target_name": "addon",
"sources": [ "hello.cc" ]
}
]
}
执行生成文件,有个重要文件即makefile
[root@haskell hello]# node-gyp configure
gyp info it worked if it ends with ok
gyp info using node-gyp@3.3.1
gyp info using node@4.4.6 | linux | x64
gyp info spawn /usr/bin/python2
接着
[root@haskell hello]# node-gyp build
gyp info it worked if it ends with ok
gyp info using node-gyp@3.3.1
gyp info using node@4.4.6 | linux | x64
make: Entering directory `/root/hello/build'
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
有个重要的文件生成,addon.node即我们需要的C++拓张模块
测试一下
// hello.js
const addon = require('./build/Release/addon');
console.log(addon.hello()); // 'world'
进一步学习
https://nodejs.org/api/addons.html