我希望使用spawn()
创建一个子进程,并且让它拥有自己的终端。
parent.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'
}
我没有找到很多参考资料,因此我使用了这个视频作为指南。
(请在回答时尽量避免使用第三方包)
console.log
吗? - Bergi[]
,改成let pipe = new net.Socket([{ fd: 3 }]);
。 - Snake_pynet.Socket
]不接受数组作为第一个参数,而是需要一个对象。 (参考链接:https://nodejs.org/api/net.html#class-netsocket) - Bergi