V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
dxcqcv
V2EX  ›  问与答

node.js 流写入后无法 rename

  •  
  •   dxcqcv · 2017-10-11 12:49:47 +08:00 · 1343 次点击
    这是一个创建于 2360 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我尝试在 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'
    

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3572 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:46 · PVG 12:46 · LAX 21:46 · JFK 00:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.