node.js流写入后无法rename
发布于 7 年前 作者 dxcqcv 3046 次浏览 来自 问答

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

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

3 回复

我在写md 自动生成文章的时候遇到过这个问题 node 生成的流文件是可以打印路径的,但是无法被 node fs api读取,因为流文件在内存里,不是 io 操作,所以读取是失败的! 我的解决方案是将文件写入一个临时文件夹里,然后读取之后将临时文件删除 image.png 最终生成的文件夹 image.png

只能用gulp吗?有没有其他方法将文件保存到临时文件夹,就这一个地方就引入gulp感觉有点浪费,非常感谢

保存到临时文件用的还是 fs api 。 gulp 只是我要处理一些流文件需要添加用到 gulp 插件而已

回到顶部