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

后端 未结 28 1739
逝去的感伤
逝去的感伤 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 03:59

    function download(url, dest, cb) {
    
      var request = http.get(url, function (response) {
    
        const settings = {
          flags: 'w',
          encoding: 'utf8',
          fd: null,
          mode: 0o666,
          autoClose: true
        };
    
        // response.pipe(fs.createWriteStream(dest, settings));
        var file = fs.createWriteStream(dest, settings);
        response.pipe(file);
    
        file.on('finish', function () {
          let okMsg = {
            text: `File downloaded successfully`
          }
          cb(okMsg);
          file.end(); 
        });
      }).on('error', function (err) { // Handle errors
        fs.unlink(dest); // Delete the file async. (But we don't check the result)
        let errorMsg = {
          text: `Error in file downloadin: ${err.message}`
        }
        if (cb) cb(errorMsg);
      });
    };
    

提交回复
热议问题