I'm writing an addon for node.js in C++ and ran into a little problem. I want to read configuration file in my module directory but unable to find it out the usual way(__dirname) as in C++ global object seems to be empty.
Is there a proper way of doing this or do I need to resort to hacks?
__dirname is not global, it is automatically added into the scope of the module when the module runs, otherwise every module would see one common directory name, which doesn't make sense.
C++ modules are passed several arguments when they are initialized, just like JS modules. In the case of modules, many of those are automatically exposed. I assume you have this in your module:
static void init (v8::Handle<v8::Object> target) {
But you have access to more arguments
static void init (v8::Handle<v8::Object> target, v8::Handle<v8::Object> module) {
So you can read the filename of the module:
v8::Local<v8::String> filename =
module->Get(v8::String::NewSymbol("filename")).As<v8::String>();
Then you can process the directory name of out of that using path:
Local<Function> require = Local<Function>::Cast(
module->Get(String::NewSymbol("require")));
Local<String> filename = module->Get(String::NewSymbol("filename")).As<String>();
Local<Value> args[] = {String::New("path")};
Local<Object> pathModule = require->Call(Object::New(), 1, args).As<Object>();
Local<Function> dirname = pathModule->Get(String::NewSymbol("dirname")).As<Function>();
Local<Value> arg2[] = {filename};
Local<String> moduleDirname = dirname->Call(pathModule, 1, arg2).As<String>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With