Friday 17 March 2017

nodejs get function from vm and use normally

I have this code

// hello.js
var hello = function() {
  return 'hello world';
};

var helloDate = function() {
  console.log(new Date());
  return 'hello world';
};

loaded with a 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();
});

but with I use localModule.helloDate() I get this error message

$ 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)

How can I use helloDate "normally" in nodejs? like use a module.



via JuanPablo

No comments:

Post a Comment