Search code examples
node.jsimageaxiosfs

Saving image in local file system using node.js


I was working on a simple code to download missing images from a site and save it in the local system, given its complete URL. I am able to get the data in binary format as response and also I am able to save it properly. But when I try to open the image it shows the format is not supported by the system. I tried to save some js and css file and they are being saved properly and I am able to view them as well. But I am having problem with all the image formats. Here is the code I wrote:

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: contains the base domain of the site
pathOfFile: contains the path of file on that domain
localBasePath: the base folder where I need to store the image
I even tried to store the response in a buffer and then tried to save the image, but still I am facing the same problem. Any suggestions would be appreciated.


Solution

  • You need to define responseEncoding while calling axios.get method.

    Change your line to:

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