node.js axios download file stream and writeFile

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

    node fileSystem writeFile encodes data by default to UTF8. which could be a problem in your case.

    Try setting your encoding to null and skip encoding the received data:

    fs.writeFile('/temp/my.pdf', response.data, {encoding: null}, (err) => {...}
    

    you can also decalre encoding as a string (instead of options object) if you only declare encoding and no other options. string will be handled as encoding value. as such:

    fs.writeFile('/temp/my.pdf', response.data, 'null', (err) => {...}
    

    more read in fileSystem API write_file

    0 讨论(0)
  • 2020-12-24 09:33

    Actually, I believe the previously accepted answer has some flaws, as it will not handle the writestream properly, so if you call "then()" after Axios has given you the response, you will end up having a partially downloaded file.

    This is a more appropriate solution when downloading slightly larger files:

    export async function downloadFile(fileUrl: string, outputLocationPath: string) {
      const writer = createWriteStream(outputLocationPath);
    
      return Axios({
        method: 'get',
        url: fileUrl,
        responseType: 'stream',
      }).then(response => {
    
        //ensure that the user can call `then()` only when the file has
        //been downloaded entirely.
    
        return new Promise((resolve, reject) => {
          response.data.pipe(writer);
          let error = null;
          writer.on('error', err => {
            error = err;
            writer.close();
            reject(err);
          });
          writer.on('close', () => {
            if (!error) {
              resolve(true);
            }
            //no need to call the reject here, as it will have been called in the
            //'error' stream;
          });
        });
      });
    }
    

    This way, you can call downloadFile(), call then() on the returned promise, and making sure that the downloaded file will have completed processing.

    0 讨论(0)
提交回复
热议问题