nodejs: C++扩展

NodejsC++扩展
首先保证nodejsv8都正确安装

下载NodeJS源码,我的放在D盘。

NodeJSC++扩展要用VS2010开发,新建一个空的Win32控制台项目,右键——属性,在常规中将目标文件扩展名改为.node

C/C++,常规中,在附加包含目录中添加NodeJS包含目录 ,D: odejsinclude

在连接器——常规中的附加库目录中添加NodeJSlib库: D: odejslib

在输入中添加附加库依赖项:node.lib

配置完毕,就可以就行扩展开发了。

新建hello.cpp

 

 1 #include <node.h>
 2 
 3 #include <string>
 4 
 5  
 6 
 7 using namespace std;
 8 
 9 using namespace v8;
10 
11  
12 
13 Handle<Value> Hello(const Arguments& args)
14 
15 {
16 
17        HandleScope scope;
18 
19        return scope.Close(String::New("Hello world!"));
20 
21 }
22 
23  
24 
25 Handle<Value> Add(const Arguments& args)
26 
27 {
28 
29   HandleScope scope;
30 
31  
32 
33   if (args.Length() < 2)
34 
35   {
36 
37     ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
38 
39     return scope.Close(Undefined());
40 
41   }
42 
43  
44 
45   if (!args[0]->IsNumber() || !args[1]->IsNumber())
46 
47   {
48 
49     ThrowException(Exception::TypeError(String::New("Wrong arguments")));
50 
51     return scope.Close(Undefined());
52 
53   }
54 
55  
56 
57   Local<Number> num = Number::New(args[0]->NumberValue() +
58 
59       args[1]->NumberValue());
60 
61   return scope.Close(num);
62 
63 }
64 
65  
66 
67 extern "C"
68 
69 {
70 
71        void init(Handle<Object> target)
72 
73        {
74 
75               NODE_SET_METHOD(target, "hello", Hello);     //对外输出hello方法
76 
77               NODE_SET_METHOD(target, "add", Add);
78 
79        }
80 
81        //输出的扩展类名hello
82 
83        NODE_MODULE(hello, init)
84 
85 }

 

 

执行命令
编译 
会在当前目录生成Release/hello.node

编写nodejs脚本hello.js

 

1 var cpphello = require('./Release/hello');
2 
3 console.log(hello.hello()); // hello world
4 
5 console.log(hello.add (2,3)); // 5

 

执行命令

按照前面文章的提示,在node目录下,执行命令行
>node hello.js
即可看到输出

hello world!

5

原文地址:https://www.cnblogs.com/cjingzm/p/3196418.html