在沙箱中执行代码,模块位于相同的上下文中

我正在自动运行ECMA-402 testing套件,针对我写的Intl polyfill,我遇到了一些问题。 目前,testing是针对库的完整版本运行的,这意味着在testing运行之前每次进行更改时都需要重新编译。 我试图通过将代码拆分成单独的模块并使用require来运行testing来改进它。

当我尝试使用vm模块运行testing时,主要的问题就变成了焦点。 如果我将polyfill添加到testing的沙箱中,那么在检查本机行为时,某些testing会失败 – 例如, Object.prototype的对象不会从testing环境的Object.prototypeinheritance。 传递require到testing将无法正常工作,因为模块仍然在父项的上下文中编译和执行。

我头脑中最简单的解决scheme是产生一个新的节点进程,并将代码写入进程的stdin ,但生成的node进程不执行写入它的代码,只是永远等待。 这是我试过的代码:

 function runTest(testPath, cb) { var test, err = '', content = 'var IntlPolyfill = require("' + LIB_PATH + '");\n'; content += LIBS.fs.readFileSync(LIBS.path.resolve(TEST_DIR, testPath)).toString(); content += 'runner();'; test = LIBS.spawn(process.execPath, process.execArgv); test.stdin.write(content, 'utf8'); // cb runs the next test test.on('exit', cb); } 

有没有人有任何想法,为什么Node.js不会执行写入其stdinstream的代码,或者如果有另一种方式,我可以让模块在与testing相同的上下文中编译?

您必须closuressubprocess的标准input才能使用数据并退出。 当你完成代码传递的时候这样做。

 test.stdin.end(); 

最后,我select使用-e命令行开关将代码直接传递给新的节点实例。 它只是稍微修改了代码:

 function runTest(testPath, cb) { var test, err = '', content = 'var IntlPolyfill = require("' + LIB_PATH + '");\n'; content += LIBS.fs.readFileSync(LIBS.path.resolve(TEST_DIR, testPath)).toString(); content += 'runner();'; test = LIBS.spawn(process.execPath, process.execArgv.concat('-e', content)); // cb runs the next test test.on('exit', cb); }