Nodejs的C++扩展
首先保证nodejs和v8都正确安装
下载NodeJS源码,我的放在D盘。
NodeJS的C++扩展要用VS2010开发,新建一个空的Win32控制台项目,右键——属性,在常规中将目标文件扩展名改为.node
在C/C++,常规中,在附加包含目录中添加NodeJS包含目录 ,D:\nodejs\include
在连接器——常规中的附加库目录中添加NodeJS的lib库: D:\nodejs\lib
在输入中添加附加库依赖项:node.lib
配置完毕,就可以就行扩展开发了。
新建hello.cpp
#include <node.h> #include <string> using namespace std; using namespace v8; Handle<Value> Hello(const Arguments& args) { HandleScope scope; return scope.Close(String::New("Hello world!")); } Handle<Value> Add(const Arguments& args) { HandleScope scope; if (args.Length() < ) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } if (!args[]->IsNumber() || !args[]->IsNumber()) { ThrowException(Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } Local<Number> num = Number::New(args[]->NumberValue() + args[]->NumberValue()); return scope.Close(num); } extern "C" { void init(Handle<Object> target) { NODE_SET_METHOD(target, "hello", Hello); //对外输出hello方法 NODE_SET_METHOD(target, "add", Add); } //输出的扩展类名hello NODE_MODULE(hello, init) }
执行命令
编译
会在当前目录生成Release/hello.node
编写nodejs脚本hello.js
var cpphello = require('./Release/hello'); console.log(hello.hello()); // hello world console.log(hello.add (2,3)); //
执行命令
按照前面文章的提示,在node目录下,执行命令行
>node hello.js
即可看到输出
hello world!
5