简体   繁体   中英

Run a Node.JS in-memory script from Node JS code

I have 2 files, app.js and performance.js .

I want to put all the code of performance.js in memory, and whenever needed run requests that reach to app.js against the code of performance.js IN MEMORY .

Notice: I don't want to store a file in memory and then download it into a temporary file

performance.js

function sum_two(a,b) { 
    return a+b;
}

module.exports = { 
    sum_two,
}

app.js:

// 1.Store performance.js in the memory somehow  // HAPPENS ONLY ONCE!
// 2.run against the memory the function sum_two // HAPPENS OVER AND OVER AGAIN
const res = sum_two(1,2);
console.log('Result:' , res);

Use new vm.compileFunction(script)() , new Function(script)() or eval(script)

// Example with esbuild
esbuild.build(esbuildConfig).then(res => {
  res[0].outputFiles.map((f) => /\.m*js$/.test(f.path) && new vm.compileFunction(f.text)())
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM