patriksimek / vm2

Advanced vm/sandbox for Node.js
MIT License
3.87k stars 295 forks source link

how require file from memfs in vm2? #472

Closed i5ting closed 1 year ago

i5ting commented 2 years ago

use require.customRequire code here:


const { NodeVM } = require('vm2');
const { fs, vol } = require('memfs');
const { patchRequire } = require('fs-monkey');

vol.writeFileSync('/index2.js', 'console.log("hi world")');
vol.writeFileSync('/index.js', `require('/index2');console.log("hi world")`);

patchRequire(vol); // new require

const vm = new NodeVM({
    require: {
        external: true,
        root: process.cwd(),
        customRequire: require
    }
});

vm.run(`
    require('/index'); 
`, 'test-with-memfs.js');

error

/Users/i5ting/workspace/github/test/node_modules/vm2/lib/bridge.js:487
                throw thisFromOtherForThrow(e);
                ^

VMError: Cannot find module '/index'
    at DefaultResolver.resolveFull (/Users/i5ting/workspace/github/test/node_modules/vm2/lib/resolver.js:251:10)
    at DefaultResolver.resolve (/Users/i5ting/workspace/github/test/node_modules/vm2/lib/resolver.js:105:15)
    at VM2 Wrapper.apply (/Users/i5ting/workspace/github/test/node_modules/vm2/lib/bridge.js:485:11)
    at requireImpl (/Users/i5ting/workspace/github/test/node_modules/vm2/lib/setup-node-sandbox.js:84:28)
    at require (/Users/i5ting/workspace/github/test/node_modules/vm2/lib/setup-node-sandbox.js:165:10)
    at test-with-memfs.js:2:5
    at VM2 Wrapper.apply (/Users/i5ting/workspace/github/test/node_modules/vm2/lib/bridge.js:485:11)
    at NodeVM.run (/Users/i5ting/workspace/github/test/node_modules/vm2/lib/nodevm.js:426:23)
    at Object.<anonymous> (/Users/i5ting/workspace/github/test/vm2.js:22:4)
    at Module._compile (node:internal/modules/cjs/loader:1095:14) {
  code: 'ENOTFOUND'
}
XmiliaH commented 2 years ago

This is currently not supported. The customRequire is not used for resolving the files but the filesystem is currently used.

i5ting commented 2 years ago

This is currently not supported. The customRequire is not used for resolving the files but the filesystem is currently used.

use unionfs maybe a good choice

i5ting commented 2 years ago
截屏2022-09-21 23 16 34
elglogins commented 1 year ago

@i5ting did you succeed with this?