我刚刚意识到我忘了更新这个问题。
这是一个工作版本,只有在调用_flush回调函数后,以及在结束事件被消耗后,才会触发结束事件(请参见
https://github.com/nodejs/node/issues/34520#issuecomment-664646155
)
const { Transform } = require('stream')
async function main() {
let resolveFlush
const flush = new Promise(resolve => {
resolveFlush = resolve
})
class Pipe extends Transform {
_transform(data, encoding, callback) {
console.log('_transform', data.toString())
this.push(data)
callback()
}
_flush(callback) {
process.nextTick(() => {
console.log('flush callback')
callback()
resolveFlush()
})
}
}
const pipe = new Pipe()
pipe.on('finish', () => {
console.log('on finish')
})
pipe.on('end', () => {
console.log('on end')
})
pipe.write('foo')
console.log('pipe.end()')
pipe.end()
console.log('read 1', pipe.read().toString())
console.log('read 2', pipe.read())
await flush
console.log('read 3', pipe.read())
}
main()
输出
_transform foo
pipe.end()
read 1 foo
read 2 null
on finish
flush callback
read 3 null
on end