{
“targets”: [
{
“target_name”: “hello”,
“sources”: [ “hello.cc” ],
“include_dirs”: [
“<!(node -e ”require(‘nan’)”)”
] }
]}
就看看这里面涉及的三个配置项:
1.target_name:表示输出出来的模块名。
2.sources:表示需要编译的源代码路径,这是一个数组。
3.include_dirs:表示编译过程中要用到的目录,这些目录中的头文件可以在预编译指令 #include 搜索到。在这里使用了一个比较特殊的写法,没有把路径用字符串常量给出,而是运行一个命令 node -e “require(‘nan’)” ,nan库后面再说,先看看这个命令输出什么: node_modulesnan ,原来这句命令的意思是返回nan库的路径。
C++编码
OK,既然已经配置了源代码是hello.cc,那就建立一个这样的文件。有一个问题需要提前提醒大家,我们所写的c++模块最终是要被v8引擎使用,所以api、写法等受到v8引擎的制约。而不同版本的nodejs其实采用的v8引擎的版本也不尽相同,这也就意味着很难用一套c++代码满足不同版本的nodejs(指编译过程,编译完成后跨版本应该能够使用,没有验证过。github不能上传二进制类库,所以github上开源会有麻烦。npm可以直接上传二进制类库,跳过编译步骤,所以问题相对较小)。
node 0.11及以上版本:
#include <node.h>
#include <v8.h>
using namespace v8;
void SleepFunc(const v8::FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
double arg0 = args[0] -> NumberValue();
Sleep(arg0);
}
void Init(Handle<Object> exports) {
Isolate* isolate = Isolate::GetCurrent();
exports->Set(String::NewFromUtf8(isolate, “sleep”),
FunctionTemplate::New(isolate, SleepFunc)->GetFunction());
}
NODE_MODULE(hello, Init);
node 0.10及以下版本:
#include <node.h>
#include <v8.h>
using namespace v8;
Handle<Value> SleepFun(const Arguments& args) {
HandleScope scope;
double arg0 = args[0] -> NumberValue();
Sleep(arg0);
return scope.Close(Undefined());
}
void Init(Handle<Object> exports) {
exports->Set(String::NewSymbol(“sleep”),
FunctionTemplate::New(SleepFun)->GetFunction());









