1

I declared a function download_file() which downloads a file using axios

async function download_file(url, filename) {
  const file_stream = fs.createWriteStream(filename);

  await axios({
    method: "GET",
    url: url,
    responseType: "stream",
  })
    .then(function (response) {
      response.data.pipe(file_stream);
    })
    .catch(function (error) {
      console.error(error);
    });

  file_stream.on("finished", () => {
    file_stream.close();
  });
}

Then I tried to download a png file and tried to read it.


await download_file(
  "https://assets.vercel.com/image/upload/v1662090959/front/nextjs/twitter-card.png",
  "twitter.png"
);

// File cannot be read properly after calling the download_file() function
const data = fs.readFileSync("twitter.png", { encoding: "utf8" });
console.log(data);

But the output is nothing.

However, when I try to read a png file without calling the download_file() function. The data is printed without any issue

This duplicate marked question doesn't solve, whats wrong with my code. As I am awaiting the call from axios, I don't need to promisify my download_file() function. Clarify if I am wrong

Artaza Sameen
  • 519
  • 1
  • 5
  • 13
  • You didn't wait when file_stream is finished so `download_file` call is finished right after you get the result from `axios` and it doesn't wait for the `file_stream` to be finished. – Anatoly Dec 21 '22 at 20:08
  • Please clarify more. It doesn't make sense . I am also awaiting the results from ```axios``` – Artaza Sameen Dec 22 '22 at 07:15
  • What exactly 'doesn't wait for the ```file_stream``` to be finished' ? What does waiting mean for file_stream to get finished ? – Phantom Dec 22 '22 at 07:42
  • It means you need to return a new promise that will be resolved in `file_stream.finished` event handler – Anatoly Dec 22 '22 at 16:45

0 Answers0