热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《我需要在节点的管道方法中等待fs.createWriteStream吗?》经验,为你挑选了1个好方法。

我非常困惑使用管道来处理写入流是否同步,因为我发现了有关回调来处理管道完成的问题

我只是想确保先完成写流,然后再执行其他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)
    })
}
}())

它可以工作,但是在读取管道文档后我感到困惑,因为它说 

默认情况下,当源Readable流发出“ 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)

哪种方法正确?非常感谢你



1> akshita007..:

您需要等待finishtempPath流上的事件。所以你可以做类似的事情

async function createTheFile() {
return new Promise(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);

基本上,我们在此处创建了一个诺言,当我们完成对tempFile的写入后,该诺言就会解决。您需要等待这一承诺,然后再继续。

但是,如果您还向流中添加一些错误处理代码(如使用node.js流进行错误处理中所述),那就太好了


推荐阅读
author-avatar
吴尧丹_449
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有