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

后端 未结 28 1992
逝去的感伤
逝去的感伤 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条回答
  •  猫巷女王i
    2020-11-22 03:57

    As Michelle Tilley said, but with the appropriate control flow:

    var http = require('http');
    var fs = require('fs');
    
    var download = function(url, dest, cb) {
      var file = fs.createWriteStream(dest);
      http.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
          file.close(cb);
        });
      });
    }
    

    Without waiting for the finish event, naive scripts may end up with an incomplete file.

    Edit: Thanks to @Augusto Roman for pointing out that cb should be passed to file.close, not called explicitly.

提交回复
热议问题