patriksimek / vm2

Advanced vm/sandbox for Node.js
MIT License
3.86k stars 293 forks source link

Unable to load external modules #503

Closed helloanoop closed 1 year ago

helloanoop commented 1 year ago

Here is my JS

const { NodeVM } = require('vm2');

const script = `
  const crypto = require('crypto-js');
`
const vm = new NodeVM({
  require: {
    external: true,
    root: ['/Users/anoop/Github/github-rest-api-collection/node_modules/crypto-js']
  }
});

vm.run(script);

Here is the error I am seeing

bruno ➤ node test.js  
/Users/anoop/bruno/bruno/node_modules/vm2/lib/bridge.js:487
                                throw thisFromOtherForThrow(e);
                                ^

VMError: Cannot find module 'crypto-js'
    at DefaultResolver.resolveFull (/Users/anoop/bruno/bruno/node_modules/vm2/lib/resolver.js:108:9)
    at DefaultResolver.resolveFull (/Users/anoop/bruno/bruno/node_modules/vm2/lib/resolver.js:315:16)
    at DefaultResolver.resolve (/Users/anoop/bruno/bruno/node_modules/vm2/lib/resolver.js:103:15)
    at ReadOnlyHandler.apply (/Users/anoop/bruno/bruno/node_modules/vm2/lib/bridge.js:485:11)
    at requireImpl (/Users/anoop/bruno/bruno/node_modules/vm2/lib/setup-node-sandbox.js:84:28)
    at require (/Users/anoop/bruno/bruno/node_modules/vm2/lib/setup-node-sandbox.js:165:10)
    at vm.js:2:18
    at VM2 Wrapper.apply (/Users/anoop/bruno/bruno/node_modules/vm2/lib/bridge.js:485:11)
    at NodeVM.run (/Users/anoop/bruno/bruno/node_modules/vm2/lib/nodevm.js:426:23)
    at Object.<anonymous> (/Users/anoop/bruno/bruno/test.js:13:4) {
  code: 'ENOTFOUND'
}

Node.js v18.13.0
helloanoop commented 1 year ago

Its important to note that I am running the script from /Users/anoop/bruno/bruno folder while attempting to load the external module from another location /Users/anoop/Github/github-rest-api-collection/node_modules/crypto-js

Is this kind of behaviour not supported ?

helloanoop commented 1 year ago

Found the fix. Closing the issue.

const { NodeVM } = require('vm2');

const script = `
  const crypto = require('crypto-js');
`
const vm = new NodeVM({
  require: {
    external: true,
    root: ['/Users/anoop/Github/github-rest-api-collection']
  }
});

vm.run(script, '/Users/anoop/Github/github-rest-api-collection/index.js`);
code4break commented 1 year ago

Adding a name even for an embedded script did the job:

const { NodeVM } = require('vm2');

const script = `
  const crypto = require('crypto-js');
`
const vm = new NodeVM({
  require: {
    external: true
  }
});

vm.run(script, 'vm2.js`);