我正在尝试从子进程向主进程发送消息,但某些块没有发送,可能是因为文件太大。
主要过程:
let response = ''
let error = ''
await new Promise(resolve => {
const p = exec(command)
p.stdout.on('data', data => {
// this gets triggered many times because the html string is big and gets split up
response += data
})
p.stderr.on('data', data => {
error += data
})
p.on('exit', resolve)
})
console.log(response)
子进程:
// only fetch 1 page, then quit
const bigHtmlString = await fetchHtmlString(url)
process.stdout.write(bigHtmlString)
我知道子进程有效,因为直接运行子进程时,可以在控制台中看到文件的结尾。但是,当我运行主进程时,我看不到文件的结尾。它很大,所以我不确定到底缺少什么。
修改:还有一个新的未知问题。当我在子进程的末尾添加等待时,它不等待,而是关闭。所以我猜它崩溃了吗?即使使用p.on('error', console.log)
,我也看不到任何错误
例如:
const bigHtmlString = await fetchHtmlString(url)
process.stdout.write(bigHtmlString)
// this never gets executed, the process closes. The wait works if I launch the child process directly
await new Promise(resolve => setTimeout(resolve, 1000000))
答案 0 :(得分:2)
process.stdout.write(...)
返回true
/ false
,具体取决于是否写入了字符串。如果返回false,则可以侦听drain
事件以确保其完成。
类似这样的东西:
const bigHtmlString = await fetchHtmlString(url);
const wrote = process.stdout.write(bigHtmlString);
if (!wrote){
// this effectively means "wait for this
// event to fire", but it doesn't block everything
process.stdout.on('drain', ...doSomethingHere)
}
答案 1 :(得分:1)