[英]How to fork a process in Node.js to run JS code from a buffer available in parent rather than from a file?
我正在使用
child_process.fork(scriptFile)
fork一個子進程並在scriptFile中執行JS。 問題是我想優化它,因為我想運行的 JS 代碼已經在父級的緩沖區中可用。 我現在將它寫入一個文件,然后指定 child_process.fork 的路徑。 這涉及兩個冗余 I/O。 首先,我將 JS 寫入父級文件中。 然后由子進程讀取。
有什么辦法可以防止這種情況嗎?
將我的評論按要求回答...
我不認為你所要求的存在。
您可以啟動一個已經在磁盤上的通用 node.js 應用程序,該應用程序在該應用程序被編碼以從 stdinput 獲取其代碼,然后您可以將您的代碼提供給 stdinput 以供存根應用程序讀取。 不會以這種方式額外讀取或寫入您的代碼。
這是執行此操作的兩個簡單應用程序的示例:
首先,從標准輸入讀取並將其作為 Javascript 執行的應用程序:
// read-from-stdin.js
let input = "";
process.stdin.on('data', function(chunk) {
input += chunk;
});
process.stdin.on('end', function() {
eval(input);
});
process.stdin.on('error', function(err) {
console.log("err:", err);
});
然后,啟動該應用程序並傳遞一些 JS 以執行的應用程序:
const spawn = require('child_process').spawn;
let child = spawn('node', ['read-from-stdin.js'], {stdio: ['pipe', 'inherit', 'inherit']});
child.on('error', function(err) {
console.log("err on spawn ", err);
});
child.stdin.write("console.log('Hello from your parent')");
child.stdin.end();
當我運行第二個代碼時,它啟動第一個代碼並通過 stdin 向它發送一個console.log()
語句,第一個應用程序中的代碼從 stdin 讀取然后執行。
從 NodeJS v14.2.0 開始,存在一個未記錄的選項,它評估腳本而不是執行模塊,請參閱test-cli-eval.js
const { fork } = require('child_process');
const script = `
process.on('message', (message) => {
if (message === 'ping') process.send('pong');
if (message === 'exit') process.exit(0);
});
`;
const child = fork('-e', [script]);
child.on('exit', (exitCode) => {
console.log(`Child process exited with ${exitCode}`)
});
child.on('message', (message) => {
if (message === 'pong') child.send('exit');
});
child.send('ping');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.