Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 是否需要在节点中的管道方法中等待fs.createWriteStream?_Node.js_Async Await_Pipe - Fatal编程技术网

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

Node.js 是否需要在节点中的管道方法中等待fs.createWriteStream?,node.js,async-await,pipe,Node.js,Async Await,Pipe,我很困惑使用管道来处理写流是否同步,因为我发现了一个关于 我只想确保在执行其他操作(如fs.rename)之前先完成写入流,因此我承诺这样做,代码如下: (async function () { await promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath}) await rename(tempPath, oldPath) function promiseTempStream({oldPath

我很困惑使用管道来处理写流是否同步,因为我发现了一个关于

我只想确保在执行其他操作(如
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)
    })
}
}())
它是有效的,但我读了之后感到困惑,因为它说

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

哪种方法正确?非常感谢

您需要等待tempPath流上的
finish
事件。所以你可以做一些像

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);
async函数createTheFile(){
返回新承诺(解决=>{
设a=replaceStream(makeRegex,replaceFn.bind(this,replaceObj),{maxMatchLen:5000});
设b=fs.createWriteStream(tempPath);
fs.createReadStream(oldPath,'utf8').pipe(a.pipe(b);
b、 在(‘完成’,解决);
}
}
等待创建文件();
重命名(临时路径、旧路径);
基本上在这里,我们已经创建了一个承诺,当我们完成写入tempFile时,这个承诺就会得到解决。在继续之前,您需要等待这个承诺

但是,如果您还向流中添加一些错误处理代码(如

中所述),那就太好了。这不是承诺,因此您不能等待它。b.on('finish',resolve);或b.on('close',resolve)?