node.js axios download file stream and writeFile

前端 未结 8 1002
花落未央
花落未央 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:22

    I have tried, and I'm sure that using response.data.pipe and fs.createWriteStream can work.


    Besides, I want to add my situation and solution

    Situation:

    • using koa to develop a node.js server
    • using axios to get a pdf via url
    • using pdf-parse to parse the pdf
    • extract some information of pdf and return it as json to browser

    Solution:

    const Koa = require('koa');
    const app = new Koa();
    const axios = require('axios')
    const fs = require("fs")
    const pdf = require('pdf-parse');
    const utils = require('./utils')
    
    app.listen(process.env.PORT || 3000)
    
    app.use(async (ctx, next) => {
          let url = 'https://path/name.pdf'
          let resp = await axios({
              url: encodeURI(url),
              responseType: 'arraybuffer'
            })
    
            let data = await pdf(resp.data)
    
            ctx.body = {
                phone: utils.getPhone(data.text),
                email: utils.getEmail(data.text),
            }
    })
    

    In this solution, it doesn't need to write file and read file, it's more efficient.

提交回复
热议问题