How can scripts that have been read into Buffer in Node.js be executed efficiently?

problem description

the script packaged by webpack is temporarily stored in memory in the form of buffer. What should I do if I want to execute this script directly?

the environmental background of the problems and what methods you have tried

try to use child_process.execFile, to find that the first parameter can only be a path, which is not applicable.

I have tried to implement it in new Function (buffer) / eval mode, and it is successful. I hope there is a better way to solve this problem.

Nov.01,2021

what you want is probably VM (Executing JavaScript)
copy an official example

const vm = require('vm');
const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// x and y are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.

document https://nodejs.org/dist/lates.

Menu