How to download a file with Node.js (without using third-party libraries)?

后端 未结 28 1283
逝去的感伤
逝去的感伤 2020-11-22 03:37

How do I download a file with Node.js without using third-party libraries?

I don\'t need anything special. I only want to download a file from a giv

28条回答
  •  时光说笑
    2020-11-22 04:12

    for those who came in search of es6-style promise based way, I guess it would be something like:

    var http = require('http');
    var fs = require('fs');
    
    function pDownload(url, dest){
      var file = fs.createWriteStream(dest);
      return new Promise((resolve, reject) => {
        var responseSent = false; // flag to make sure that response is sent only once.
        http.get(url, response => {
          response.pipe(file);
          file.on('finish', () =>{
            file.close(() => {
              if(responseSent)  return;
              responseSent = true;
              resolve();
            });
          });
        }).on('error', err => {
            if(responseSent)  return;
            responseSent = true;
            reject(err);
        });
      });
    }
    
    //example
    pDownload(url, fileLocation)
      .then( ()=> console.log('downloaded file no issues...'))
      .catch( e => console.error('error while downloading', e));
    

提交回复
热议问题