node.js axios download file stream and writeFile

前端 未结 8 987
花落未央
花落未央 2020-12-24 08:50

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         


        
8条回答
  •  北海茫月
    2020-12-24 09:30

    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.

提交回复
热议问题