【问题标题】:Node.js | fs.readFileSync cannot find file that has just been saved in a folderNode.js | fs.readFileSync 找不到刚刚保存在文件夹中的文件
【发布时间】:2021-12-10 06:37:57
【问题描述】:

在下面的代码中,我遍历了一组图像 URL,对于每个图像 URL,我下载了图像并将其保存在一个文件夹中:

function downloadImg (url, imagePath) {
  axios({ url, responseType: 'stream' }).then((response) => {
    return new Promise((resolve, reject) => {
      response.data
        .pipe(fs.createWriteStream(imagePath))
        .on('finish', () => resolve())
        .on('error', e => reject(e));
    })
  })
}

for (const img of imgs) {
  let imgPath = `${__dirname}/temp/${img.id}.jpg`
  let downloadedImg = await downloadImg(img.media_url, imgPath)
  console.log(imgPath) // returns the correct path
  console.log(fs.existsSync(imgPath)) // returns false
  
  // throws fs.readFileSync Error: "no such file or directory, open {imgPath}"
  doSomethingWith(imgPath)
}

然后当我点击我的/temp 文件夹时,图像文件就在那里并且正在工作。

我做错了什么?

【问题讨论】:

    标签: node.js async-await fs


    【解决方案1】:

    将 axios 请求包装在 Promise 中,而不是反过来修复它:

    function downloadImg (url, imagePath) {
      return new Promise((resolve, reject) => {
        axios({ url, responseType: 'stream' }).then((response) => {
          response.data
            .pipe(fs.createWriteStream(imagePath))
            .on('finish', () => resolve())
            .on('error', e => reject(e))
        })
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 2020-07-29
      • 2013-08-02
      相关资源
      最近更新 更多