Skip to content

Require does not work as expected within vm #2503

@reggi

Description

@reggi

I decided to port this over from stackoverflow because it's so specific to node & vm.

The code below uses the native node vm library, which allows you to evaluate javascript strings in different contexts.

The particular code within example.js there's a javascript string that adds a property .marker with the value true to the Array global variable, then requires a file global.js (seen below), then logs Array.marker. The code below logs true.

var vm = require('vm')

var code = [
  'Array.marker = true',
  "require('./global.js')",
  'console.log(Array.marker)', // => true
].join('\n')

var script = new vm.Script(code, { filename: 'example.js' })

script.runInNewContext({
  'require': require,
  'console': console
})

Below is the contents of global.js, which is a simple module that changes the value of Array.marker to false.

var hi = function () {
  Array.marker = false
}
module.exports = hi()

What should be happening here is that the code within the vm should be setting Array.marker to true then the global.js module should be changing it the value to false and it should log false.

If you go ahead and run the contents of the javascript string outside of vm, in it's own file, you will get the expected result, Array.marker will be equal to false.

Array.marker = true
require('./global.js')
console.log(Array.marker) // => false

The question is: Why doesn't Array.marker get updated to the correct value (true)? How can I allow the value of Array.marker to get updated from within the global.js module?

Is this an issue with the native node.js vm module? Or is this not supposed to be possible? Or are my settings off?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionIssues that look for answers.vmIssues and PRs related to the vm subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions