Skip to content

Instantly share code, notes, and snippets.

@fridgerator
Last active April 3, 2019 17:01
Show Gist options
  • Save fridgerator/fb0d9d66095e1e59d8285ae141a00f3e to your computer and use it in GitHub Desktop.
Save fridgerator/fb0d9d66095e1e59d8285ae141a00f3e to your computer and use it in GitHub Desktop.
v8 Boilerplate
{
"targets": [
{
"target_name": "hello",
"sources": [
"src/main.cc",
],
"include_dirs": [
"<!(node -e \"require('nan')\")"
]
}
]
}
#include <node.h>
#include <nan.h>
class Hello : public Nan::ObjectWrap {
public:
static NAN_MODULE_INIT(Init);
private:
explicit Hello();
~Hello();
static NAN_METHOD (New);
static NAN_METHOD (Go);
static inline Nan::Persistent<v8::Function> & constructor() {
static Nan::Persistent<v8::Function> my_constructor;
return my_constructor;
}
};
Hello::Hello() {}
Hello::~Hello() {}
NAN_MODULE_INIT(Hello::Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Hello").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
Nan::SetPrototypeMethod(tpl, "go", Go);
constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target, Nan::New("Hello").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
NAN_METHOD(Hello::New) {
if (info.IsConstructCall()) {
Hello * obj = new Hello();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
Nan::ThrowError("must use `new`");
}
}
NAN_METHOD(Hello::Go) {
info.GetReturnValue().Set(Nan::New("hello world").ToLocalChecked());
}
NODE_MODULE(objectWrapper, Hello::Init)
{
"name": "hello",
"version": "1.0.0",
"main": "./build/Release/hello.node",
"license": "proprietary",
"private": true,
"scripts": {
"install": "node-gyp rebuild",
"compile": "node-gyp rebuild"
},
"dependencies": {
"nan": "^2.13.2",
"node-gyp": "^3.8.0"
},
"gypfile": true
}
const Hello = require('./build/Release/hello').Hello
let h = new Hello()
console.log(h.go()) // "hello world"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment