The module property is undefined when using vm.runInThisContext

5.7k Views Asked by At

Here is a function from jasmine 2.0.0 standalone project:

function getJasmineRequireObj() {
    if (typeof module !== "undefined" && module.exports) {
        return exports;
    } else {
        window.jasmineRequire = window.jasmineRequire || {};
        return window.jasmineRequire;
    }
}

I guess that if I would use the standard require method the module property will be define. When I load this file using the VM module as follows the module global property is undefined:

var fs = require('fs');
var vm = require('vm');
var jasmineFile = fs.readFileSync(__dirname + '/jasmine.js');
vm.runInThisContext(src, jasmineFile);

Is this the expected behavior of the VM module or a defect?

1

There are 1 best solutions below

4
On BEST ANSWER

It is the expected behaviour. Your code is evaluated in the same context, but not in the same scope, so module, exports and whatnot are undefined. You can do something like this:

var m = require('module')
var src = 'module.exports = 42'
var res = require('vm').runInThisContext(m.wrap(src))(exports, require, module, __filename, __dirname)
console.log(module.exports)

but there is no much point in doing that, because it's basically what require does