我有这段代码
// hello.js
var hello = function() {
return 'hello world';
};
var helloDate = function() {
console.log(new Date());
return 'hello world';
};
加载了nodejs vm
//test/test_hello.js
var sinon = require('sinon');
var vm = require('vm');
var fs = require('fs');
var source = fs.readFileSync('./hello.js').toString();
var local = new vm.createContext({});
var script = new vm.Script(source);
script.runInContext(local);
var localModule = {};
for (var o in local) {
localModule[o] = local[o];
}
before(function() {
});
it('hello', function() {
local.hello();
});
it('helloDate', function () {
localModule.helloDate();
});
但是我使用localModule.helloDate()
我收到此错误消息
$ mocha
✓ hello
1) helloDate
1 passing (7ms)
1 failing
1) helloDate:
ReferenceError: console is not defined
at Object.helloDate (evalmachine.<anonymous>:6:3)
at Context.<anonymous> (test/test_hello.js:26:15)
我如何使用helloDate
&#34;通常&#34;在nodejs?比如使用模块的功能。
答案 0 :(得分:0)
尝试将控制台传递给vm上下文,如下所示:
var local = new vm.createContext({console: console});