简体   繁体   English

我是否需要在节点中的管道方法中等待fs.createWriteStream?

[英]Do I need await fs.createWriteStream in pipe method in node?

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: 我只想确保写入流完成之前做其他像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)
    })
}
}())

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. 默认情况下,当源可读流发出'end'时,在目标可写流上调用stream.end(),以便目标不再可写。

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 非常感谢你

You need to wait for the finish event on the tempPath stream. 您需要等待tempPath流上的finish事件。 So you could do something like 所以你可以做点什么

async function createTheFile() {
return new Promise<void>(resolve => {
    let a = replaceStream(makeRegex, replaceFn.bind(this, replaceObj), { maxMatchLen: 5000 });
    let b = fs.createWriteStream(tempPath);
    fs.createReadStream(oldPath, 'utf8').pipe(a).pipe(b);
    b.on('finish', resolve);
}
}

await createTheFile();
rename(tempPath, oldPath);

Basically here we have created a promise that resolves when we have completed writing into the tempFile. 基本上我们已经创建了一个在我们完成写入tempFile时解析的promise。 And you need to await that promise before proceeding ahead. 在继续前进之前,你需要等待这个承诺。

However it would be great if you also add some error handing code with the streams as mentioned in Error handling with node.js streams 但是,如果您还使用node.js流的错误处理中提到的流添加一些错误处理代码,那将会很棒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM