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