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

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

    Here's yet another way to handle it without 3rd party dependency and also searching for redirects:

            var download = function(url, dest, cb) {
                var file = fs.createWriteStream(dest);
                https.get(url, function(response) {
                    if ([301,302].indexOf(response.statusCode) !== -1) {
                        body = [];
                        download(response.headers.location, dest, cb);
                      }
                  response.pipe(file);
                  file.on('finish', function() {
                    file.close(cb);  // close() is async, call cb after close completes.
                  });
                });
              }
    
    

提交回复
热议问题