使用 node.js 在本地文件系统中保存图像

Saving image in local file system using node.js

我正在编写一个简单的代码,用于从站点下载丢失的图像并将其保存在本地系统中,前提是它是完整的 URL。我能够以二进制格式获取数据作为响应,而且我能够正确保存它。但是当我尝试打开图像时,它显示系统不支持该格式。我试图保存一些 js 和 css 文件,它们被正确保存,我也可以查看它们。但是我对所有图像格式都有疑问。 这是我写的代码:

try {
  response = await axios.get(domain + pathOfFile);
  console.log(response);
  fs.writeFile(localBasePath + pathOfFile, response.data, "binary", (error) => {
    if (error) console.log("error while writting file", error.message);
  });
} catch (error) {
  console.log("error in getting response", error.message);
}

domian: 包含站点的基础域
pathOfFile: 包含该域上的文件路径
localBasePath:我需要存储图片的基本文件夹
我什至尝试将响应存储在缓冲区中,然后尝试保存图像,但我仍然面临同样的问题。 如有任何建议,我们将不胜感激。

调用axios.get方法时需要定义responseEncoding

将您的线路更改为:

response = await axios.get(domain + pathOfFile, {responseEncoding: "binary"});