Skip to content

Instantly share code, notes, and snippets.

@AndiSHFR
Created May 3, 2018 06:44
Show Gist options
  • Save AndiSHFR/6b9d3980078704d103c6d8417fccda19 to your computer and use it in GitHub Desktop.
Save AndiSHFR/6b9d3980078704d103c6d8417fccda19 to your computer and use it in GitHub Desktop.
Node.js - add constat values to exports of native addon
#define NODE_SET_MEMBER(target, name, value) \
do { \
v8::Isolate* isolate = target->GetIsolate(); \
v8::Local<v8::Context> context = isolate->GetCurrentContext(); \
v8::Local<v8::String> constant_name = v8::String::NewFromUtf8(isolate, (name)); \
(target)->Set(v8::Local<Value>::New(isolate, \
v8::String::NewFromUtf8(isolate, name)), \
value); \
} while (0)
#define DEFINE_CONSTANT(target, name, constant) \
do { \
v8::Isolate* isolate = target->GetIsolate(); \
v8::Local<v8::Context> context = isolate->GetCurrentContext(); \
v8::Local<v8::String> constant_name = v8::String::NewFromUtf8(isolate, (name)); \
v8::Local<v8::Number> constant_value = v8::Number::New(isolate, static_cast<double>(constant)); \
v8::PropertyAttribute constant_attributes = static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); \
(target)->DefineOwnProperty(context, \
constant_name, \
constant_value, \
constant_attributes) \
.FromJust(); \
} while (0)
enum ServiceStatus {
START_PENDING = 0x04,
RUNNING = 0x03,
STOP_PENDING = 0x02,
STOPPED = 0x01,
};
void initializeModule(v8::Local<Object> exports) {
v8::Local<Object> serviceStatus = v8::Object::New(isolate);
DEFINE_CONSTANT(serviceStatus, "START_PENDING", ServiceStatus::START_PENDING);
DEFINE_CONSTANT(serviceStatus, "RUNNING", ServiceStatus::RUNNING);
DEFINE_CONSTANT(serviceStatus, "STOP_PENDING", ServiceStatus::STOP_PENDING);
DEFINE_CONSTANT(serviceStatus, "STOPPED", ServiceStatus::STOPPED);
NODE_SET_MEMBER(exports, "ServiceStatus", serviceStatus);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, initializeModule)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment