3

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?

Ikaso
  • 2,268
  • 19
  • 26

1 Answers1

15

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

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
  • 2
    So why would someone use the runInConext method if it makes life difficult? – Ikaso Jan 03 '14 at 12:45
  • `runInThisContext` is used as a stable alternative to `eval`, plus it allows setting file name. I don't think it is really useful, but is used in node core, so why not expose it? – vkurchatkin Jan 03 '14 at 12:51
  • yeah, if I do this, I get things like "console" is not defined. – Alexander Mills Jul 29 '17 at 19:34
  • 1
    I will tell you a valid usecase at present the esm loader of nodejs don't supports import from url with this i can easy use this to extend it with fetch runInthisContext – frank-dspeed Dec 29 '19 at 06:17