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

后端 未结 28 1205
逝去的感伤
逝去的感伤 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:19

    Don't forget to handle errors! The following code is based on Augusto Roman's answer.

    var http = require('http');
    var fs = require('fs');
    
    var download = function(url, dest, cb) {
      var file = fs.createWriteStream(dest);
      var request = http.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
          file.close(cb);  // close() is async, call cb after close completes.
        });
      }).on('error', function(err) { // Handle errors
        fs.unlink(dest); // Delete the file async. (But we don't check the result)
        if (cb) cb(err.message);
      });
    };
    
    0 讨论(0)
  • 2020-11-22 04:21

    We can use the download node module and its very simple, please refer below https://www.npmjs.com/package/download

    0 讨论(0)
  • 2020-11-22 04:22

    Without library it could be buggy just to point out. Here are a few:

    • Can't handle http redirection, like this url https://calibre-ebook.com/dist/portable which is binary.
    • http module can't https url, you will get Protocol "https:" not supported.

    Here my suggestion:

    • Call system tool like wget or curl
    • use some tool like node-wget-promise which also very simple to use. var wget = require('node-wget-promise'); wget('http://nodejs.org/images/logo.svg');
    0 讨论(0)
  • 2020-11-22 04:22

    You can try using res.redirect to the https file download url, and then it will be downloading the file.

    Like: res.redirect('https//static.file.com/file.txt');

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