Sloppy's Blog

NodeJS C++扩展入门(1)

环境的准备

  • NodeJS本身的安装
  • NodeJS的c++扩展是借助node-gyp进行编译的,所以我们需要安装node-gyp,在命令行下输入:npm install node-gyp -g(可能需翻墙)

新建一个文件夹,作为我们的主目录,这里我们新建一个hello目录,

  • 编写binding.gyp文件,内容如下:
          {
            'targets': [
              {
                'target_name': 'hello',
                'sources': [
                    'src\hello.cc'
                ]
              }
            ]
          }
      
  • 编写cpp文件,我们取名叫hello.cc吧,内容如下:
  •   include 
      include 
      using v8::FunctionCallbackInfo;
      using v8::Isolate;
      using v8::Local;
      using v8::Object;
      using v8::String;
      using v8::Value;
      void Method(const FunctionCallbackInfo& args) {
          Isolate* isolate = args.GetIsolate();
          args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello world"));
      }
      void init(Local exports) {
          NODE_SET_METHOD(exports, "hello", Method);
      }
      NODE_MODULE(hello, init)
      

编译

在Hello目录位置打开命令行:输入命令:node-gyp configure build,不出意外,一会显示ok字样

编写test.js进行测试:


const addon = require(‘./build/Release/hello.node’);
console.log(addon.hello()); // ‘Hello world’

在命令行输入:node test.js 打印出 ‘Hello world’

参考资料:https://nodejs.org/dist/latest-v4.x/docs/api/addons.html