Sunday, 9 April 2017

exports is not defined when running node.js script using vm in strict mode

I see this code in many modules:

var app = exports = module.exports = {};

But I have some problem executing these modules using Node.js VM in strict mode.

Here a demonstration:

var code = `
'use strict'; // Works if I remove this line
var app = exports = module.exports;
`;

var vm = require('vm');
var vmModule = { exports: {} };
var context = vm.createContext({
  exports: vmModule.exports,
  module: vmModule
});
var script = new vm.Script(code);

script.runInContext(context);
console.log("ok");

If I run this code I receive a exports is not defined error. Without use strict the above code works fine.

Why a similar declaration works on a standard Node module but not inside a vm script? Should I declare the context in a different way?



via Davide Icardi

No comments:

Post a Comment