【发布时间】:2018-03-26 22:03:11
【问题描述】:
我很困惑使用管道处理写入流是否同步,因为我发现了一个关于callback to handle completion of pipe的问题
我只是想确保写入流在其他人之前完成,例如fs.rename,所以我承诺它,代码如下:
(async function () {
await promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath})
await rename(tempPath, oldPath)
function promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath}) {
return new Promise((res, rej) => {
const writable = fs.createWriteStream(tempPath)
fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(writable)
writable
.on('error', (err) => {rej(err)})
.on('finish', res)
})
}
}())
它有效,但我在阅读pipe doc 后感到困惑,因为它说
默认情况下,当源可读流发出'end'时,在目标可写流上调用stream.end(),因此目标不再可写。
所以我只需要
await fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(fs.createWriteStream(tempPath))
await rename(tempPath, oldPath)
或者只是
fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(fs.createWriteStream(tempPath))
await rename(tempPath, oldPath)
哪种方法是正确的?非常感谢
【问题讨论】:
-
这不是一个承诺,所以你不能
await它。
标签: node.js async-await pipe