I am very confuse using pipe to handle write stream is sync or not, because I find a question about callback to handle completion of pipe
I just wanna ensure the write stream is done before do others like fs.rename
, so I promisify it, code like:
(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)
})
}
}())
It works, but I’m confused after read pipe doc, because it says
By default, stream.end() is called on the destination Writable stream when the source Readable stream emits 'end', so that the destination is no longer writable.
So I only need
await fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(fs.createWriteStream(tempPath))
await rename(tempPath, oldPath)
or just
fs.createReadStream(oldPath, 'utf8')
.pipe(replaceStream(makeRegex ,replaceFn.bind(this, replaceObj), {maxMatchLen: 5000}))
.pipe(fs.createWriteStream(tempPath))
await rename(tempPath, oldPath)
which is right way to do it? thank you very much