繁体   English   中英

如何在 Node.js 中 fork 进程以从父级中可用的缓冲区而不是文件中运行 JS 代码?

[英]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.

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