My Problem
I'm writing a node
module called a
, which require()
s a module b
(written by a stranger). Unfortunately, a
doesn't only need to access the public members - it also needs to access local variables declared in the scope of the module.
// a
var b = require('b');
console.log(b.public);
console.log(b.private); // undefined
// b
var c = require('c');
var stdin = process.stdin;
exports.public = true;
var private = true;
My Solution
// a
var b = require('b');
var srcPath = require.resolve('b');
console.log(b.public);
fs.readFile(srcPath, 'utf-8', function (err, src) {
var box = {};
var res = vm.runInNewContext(src, box, srcPath);
console.log(box.private);
});
But vm
doesn't run b
as a module, so require()
etc. aren't accessible from the context of the vm
. So there are ReferenceError
s like:
var res = vm.runInNewContext(src, box, scPath);
^
ReferenceError: require is not defined
at <module b>
at <module a>
at fs.readFile (fs.js:176:14)
at Object.oncomplete (fs.js:297:15)
My Question
Which is the cleanest way to get the value of a local variable declared in another module? Ideas?
Thanks for your help.
b
was written by a stranger and not by me (and I don't want to get my hands dirty). - Any other ideas? – Transcendent