NAN is introduced

NAN’s full name is Native Abstraction for Node.js, which is presented as a Node.js package. Once installed, you get a bunch of C++ header files with a bunch of macros inside. It mainly provides packaged macros across Node.js and V8 versions, so developers don’t have to worry about API differences between versions. A dozen C++ extensions from nodejs

The advantage of NAN is that it can mask different versions of Node’s API, making C++ extensions available to wirte once, compile anywhere, a C++ extension that works with different versions of node.js. The c++ extension implements a summation extension (hello world is too many, write a different one).

Extend the address is: www.npmjs.com/package/sum…

Project code address: github.com/warjiang/de…

The usage is as follows:

The project catalog is as follows:

npm install nan -S

sum.node
<! (node -e \"require('nan')\")
<!
node -e "require('nan')"

C++ part development

SRC /init.cc:

#include <v8.h>
#include <node.h>
#include <nan.h>
using v8::Local;
using v8::Object;
using v8::Number;

NAN_METHOD(sum){
    Nan::HandleScope scope;
    uint32_t sum = 0;
    for(int i = 0; i< info.Length(); i++){
        sum += info[i]->NumberValue();
    }
    info.GetReturnValue().Set(Nan::New(sum));
}

void init (Local<Object> exports)
{
    Nan::HandleScope scope;
    Nan::SetMethod(exports, "sum", sum);
}

NODE_MODULE(memwatch, init);
Copy the code

Extension entry from NODE_MODULE(memwatch, init); Initially, the js layer requires (‘path/to/xxx.node’) init function is executed. The input of the init function can be analogous to the module.exports object, where we add a method named sum to the exports object. The corresponding implementation is the NAN_METHOD(sum) part. Sum = sum; sum = sum; sum = sum; sum = sum; sum = sum; sum = sum; Set(Nan::New(sum))) to return sum. Node.node.build = node-gyp configure && Node-gyp build = node-gyp build = node-gyp build = node-gyp build We can verify this by launching a Node command line:

// node cli
> let addon = require('./build/Release/sum')
> addon.sum(1) // 1
> addon.sum(1,2) // 3
Copy the code

The way of referring to build/Release/sum is very inconvenient in actual development. We can use JS to encapsulate this line of code, reference build/Release/sum inside JS, and expose the method for external invocation.

Js part development

With the above foundation, it seems very natural for us to develop the JS part here. Go straight to code

const addon = require('./build/Release/sum')
module.exports = addon.sum
Copy the code

Two lines of code, clear and simple, expose the sum method by referring to the compiled extension.

release

When the nodejs extension is released, the install hook should be added to the scripts section of package.json as follows:

node-gyp rebuild
npm publish