NodeJS vm.runInThisContext()缺less__filename

每当我运行vm.runInThisContext(code, filename) ,我运行的代码报告__filename__dirnameundefined

这也导致了任何fs.readFile和这样的调用都不能使用相对path。 实际上,文件系统function根本不起作用,即使我给它们提供硬编码的绝对path到现有的文件。

例如,这将无能为力:

 var fs = require('fs'); fs.readFile('/home/test/file.txt', function(e, data) { if (e) {throw e;} console.log('here i am'); }); 

发生什么事是没有任何反应。 如果我在正常的NodeJS代码中运行代码,那么它输出“我在这里”,但如果我通过vm模块运行该代码,则什么都不会发生。 callback是根本不会被调用的,因为由于某种原因,它不能find文件,也似乎没有任何超时。

我如何让节点明白,执行的代码是一些“文件”,也使fs模块function工作? 我试着指定vm.runInThisContext(code, filename)的第二个参数,但我没有看到任何区别。 看起来Node几乎不关心第二个参数。

我不确定我以前的代码示例是如何工作的,因为现在他们根本不工作。

我发现你可以使用vm.runInNewContext(code, sandbox, filename) ,然后在沙箱中指定require__filename和任何你需要的:

 // 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); 

那么如果我运行node bootstrap.js --debug它工作正常!