gpt4 book ai didi

javascript - 与 spawn() 子进程通信?

转载 作者:行者123 更新时间:2023-12-05 00:29:21 27 4
gpt4 key购买 nike

我正在尝试使用 spawn() 创建子进程有自己的终端
父.js:

const spawn = require('child_process').spawn;

console.log('started parent process...'); //this should be printed in the parent terminal

const child = spawn('start node', [`child.js`], {
cwd:__dirname,
shell: true,
stdio: [null, null, null, 'pipe']
});

const Name = 'general kenobi';

child.stdio[3].write(Name);

child.stdio[3].on('data', (data) => {
console.log('data=>', data.toString());
child.kill();
});
child.js:
console.log('started child process...');

(async()=>{
await new Promise(r=>setTimeout(r,3000));

try{
let net = require('net');
let pipe = new net.Socket({ fd: 3 });

pipe.on('data',(data)=>{
pipe.write(`hello there ${data}`);
});
}catch(err){console.log(err)}
await new Promise(r => setTimeout(r, 3000));
})();
预期数据应为 data=> hello there general kenobi但它在子终端中给出了这个错误
 throw new ERR_INVALID_FD_TYPE(type);
^

TypeError [ERR_INVALID_FD_TYPE]: Unsupported fd type: UNKNOWN
at new NodeError (node:internal/errors:371:5)
at createHandle (node:net:152:9)
at new Socket (node:net:340:20)
at Object.<anonymous> (C:\...\parent.js:4:12)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'ERR_INVALID_FD_TYPE'
}

我找不到很多引用资料,所以我使用了 this video作为指导
(请在回答时尽量避免使用第 3 方包裹)

最佳答案

删除 shell: true并将命令更改为 parent.js 中的“Node ”文件。

const child = spawn('node', [`child.js`], {
cwd:__dirname,
stdio: [null, null, null, 'pipe']
});
而不是使用 spawn 本身,同时添加 shell: true , spawn 将使用 shell of your system运行该命令。一般来说,我建议使用纯产卵而不使用外壳。不直接接触外壳和管道数据问题的风险将降低。

关于javascript - 与 spawn() 子进程通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69906241/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com