node.js 流写入后无法 rename

2017-10-11 12:49:47 +08:00
 dxcqcv

我尝试在 writeStream 完成后 rename 文件名,promisify 了 rename 和 writeStream 并使用 async/await 来模拟同步,但遇到报错在 writeStream 完成后 rename 无法找到文件,但打印文件路径都能得到,请高手指点, 大致代码如下

async path => {
  const tempPath = `${path}Temp`
  //oldPath, 读取的文件 
  //makeRegex, 正则替换规则
  //replaceFn, 替换函数
  //replaceObj, 替换对象
  await promiseTempStream({oldPath, makeRegex, replaceFn, replaceObj, tempPath})
  console.log(fs.existsSync(tempPath)) // 输出 true
  console.log(tempPath) // 输出路径正常
  await promiseRename(tempPath, oldPath)
}

function promiseRename(oldPath, newPath) {
  return new Promise((res, rej) => {
  console.log(11111)
  console.log(oldPath) // output static\projects\lotteryNine-40\index.htmlTemp
  console.log(newPath) // output ./static/projects/lotteryNine-40/index.html
  console.log(11111)
  fs.rename(oldPath, newPath, (err) =>{
    if(err) rej(err)
    res()
    })
  })
}

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()})
   })
}

报错信息为

Error: ENOENT: no such file or directory, open 'D:\dev\github\auto-activity\static\projects\lotteryNine-40\index.htmlTemp'

我很奇怪,既然能打印出文件路径为什么还会报找不到文件呢?

1376 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/396734

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX