Executes code in sandbox using vm
package.
const assert = require('assert/strict');
const { run } = require('vmtx');
assert.strictEqual(execute('123'), 123);
Path to file is resolved against working directory.
run(`require('./path/to/file')`);
But can also be resolved against custom directory.
run({
code: 'require("./path/to/file")',
rootdir: './path/to/dir',
});
const { runFile } = require('vmtx');
runFile('./path/to/file');
run({
code: 'a + b',
variables: {
a: 1,
b: 2,
},
});
Variables are visible only in main code.
run({
code: 'doSomething();',
globals: {
doSomething() { }
},
});
Unlike variables globals are visible in other modules also.
run({
code: `
const myModule = require("my-test");
const myFile = require("./my-file");
console.log(myModule.myData);
console.log(myFile.myData);
`,
loadModule(moduleName) {
if (moduleName === 'my-test') {
return { myData: 'Hello World' };
}
return null;
},
isFile(filepath) {
return filepath === path.resolve('./my-file.js');
},
readFile(filepath) {
if (filepath === path.resolve('./my-file.js')) {
return { myData: 'Hello World' };
}
},
});
run({
code: 'doSomeLongRunningTask()',
timeout: 30,
});