NodeJS vm.runInThisContext() and lack of __filename
Whenever I run vm.runInThisContext(code, filename)
, the code I ran reports __filename
and __dirname
as undefined
.
This also leads to the situation that any fs.readFile
and such calls will not work with relative paths. Actually to be exact, file system functions do not work at all even if I feed them a hard-coded absolute path to an existing file.
For example, this will do nothing:
var fs = require('fs');
fs.readFile('/home/test/file.txt', function(e, data) {
if (e) {throw e;}
console.log('here i am');
});
What happens is that nothing happens. If I run the code in normal NodeJS code then it outputs "here i am", but if I run that code through the vm
module, then nothing happens. The callback is simply never called, because for some reason it can't locate the file and there does not seem to be a开发者_如何学Cny timeouts either.
How can I make Node to understand that the executed code is some "file" and also make the fs
module functions to work? I tried specifying the second parameter to vm.runInThisContext(code, filename)
, but I see no difference. It almost looks that Node doesn't care about the second parameter.
I'm not exactly sure how I even got my code examples to work before, because right now they do not work at all.
I found out that you can use vm.runInNewContext(code, sandbox, filename)
and then specify require
, __filename
and whatever you need in the sandbox:
// Place here some path to test it. I'm using Cygwin...
var filename = '/cygdrive/z/www/project/src/bootstrap.js';
var code = "var fs = require('fs'); fs.readFile('./path/to/some/file.js', function(e, data) {if (e) {throw e;} console.log(data.toString());});";
var vm = require('vm');
vm.runInNewContext(code, {
require: require,
console: console,
__filename: filename
}, filename);
Then if I run node bootstrap.js --debug
it works fine!
精彩评论