You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js | fs.readFileSync无法读取刚保存到文件夹的文件

问题原因

你编写的downloadImg函数没有显式返回Promise对象,导致await关键字没有等待异步下载流程执行完成就继续向下执行了,此时文件还没完成写入甚至还未创建,自然会检测不到文件存在。当你手动打开文件夹查看时,后台的异步下载流程已经执行完毕,所以能看到正常可打开的图片文件。

修复方案
  • 给downloadImg函数加上return语句,将axios调用产生的Promise链整体返回,这样await才能正确等待下载写入流程结束
    修正后的代码如下:
function downloadImg (url, imagePath) {
  // 此处添加return,返回整个Promise链
  return 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));
    })
  })
}
  • 可选补充异常捕获逻辑,避免下载失败时抛出未处理的Promise异常:
for (const img of imgs) {
  try {
    let imgPath = `${__dirname}/temp/${img.id}.jpg`
    await downloadImg(img.media_url, imgPath)
    console.log(imgPath)
    console.log(fs.existsSync(imgPath)) // 此时会返回true
    doSomethingWith(imgPath)
  } catch (e) {
    console.error('图片下载处理失败:', e)
  }
}

内容的提问来源于stack exchange,提问作者user2272048

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:06:03