我有用例,比如运行一个进程。当在其他文件中调用该进程的退出代码时,我需要分离实现。例如,应用程序运行ping过程。在特定的事件中,从应用程序可以杀死进程。
问题是不能返回ping实例。还没有定义。
ping.js
const { spawn } = require('child_process');
class Ping {
flags: string[];
constructor(flags: string[]) {
this.flags = [...flags]
}
run() {
const ping = spawn('ping', this.flags);
ping.on('spawn', () => {
return ping
})
}
}
export = Pingapplication.js
const Ping = require('ping.js');
const duration = 5000;
const end_time = Date.now() + duration;
const flags = ['-t', 'stackoverflow.com'];
const ping = new Ping(flags)
const pingProcess = ping.run();
pingProcess.stdout.on('data', chunk => {
console.log(chunk.toString())
})
while(true) {
const current_time = Date.now();
if (current_time > end_time) {
pingProcess.kill()
break;
}
}发布于 2022-08-05 14:20:20
您可以在生成子进程后立即返回它:
class Ping {
flags: string[];
constructor(flags: string[]) {
this.flags = [...flags]
}
run() {
const ping = spawn('ping', this.flags);
ping.on('error', () => {
/* error handling logic */
})
return ping
}
}https://stackoverflow.com/questions/73250945
复制相似问题