i want download a pdf file with axios
and save on disk (server side) with fs.writeFile
, i have tried:
axios.get(\'https://xxx/my.pd
The problem with broken file is because of backpressuring in node streams. You may find this link useful to read: https://nodejs.org/es/docs/guides/backpressuring-in-streams/
I'm not really a fan of using Promise base declarative objects in JS codes as I feel it pollutes the actual core logic & makes the code hard to read. On top of it, you have to provision event handlers & listeners to make sure the code is completed.
A more cleaner approach on the same logic which the accepted answer proposes is given below. It uses the concepts of stream pipelines.
const util = require("util");
const stream = require("stream");
const pipeline = util.promisify(stream.pipeline);
const downloadFile = async () => {
try {
await pipeline( axios.get('https://xxx/my.pdf', {responseType: 'blob'}),
fs.createWriteStream("/temp/my.pdf"));
console.log("donwload pdf pipeline successfull");
} catch (error) {
console.error("donwload pdf pipeline failed", error);
}
}
exports.downloadFile = downloadFile
I hope you find this useful.