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

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

    Based on the other answers above and some subtle issues, here is my attempt.

    1. Only create the fs.createWriteStream if you get a 200 OK status code. This reduces the amount of fs.unlink commands required to tidy up temporary file handles.
    2. Even on a 200 OK we can still possibly reject due to an EEXIST file already exists.
    3. Recursively call download if you get a 301 Moved Permanently or 302 Found (Moved Temporarily) redirect following the link location provided in the header.
    4. The issue with some of the other answers recursively calling download was that they called resolve(download) instead of download(...).then(() => resolve()) so the Promise would return before the download actually finished. This way the nested chain of promises resolve in the correct order.
    5. It might seem cool to clean up the temp file asynchronously, but I chose to reject only after that completed too so I know that everything start to finish is done when this promise resolves or rejects.
    const https = require('https');
    const fs = require('fs');
    
    /**
     * Download a resource from `url` to `dest`.
     * @param {string} url - Valid URL to attempt download of resource
     * @param {string} dest - Valid path to save the file.
     * @returns {Promise} - Returns asynchronously when successfully completed download
     */
    function download(url, dest) {
      return new Promise((resolve, reject) => {
        const request = https.get(url, response => {
          if (response.statusCode === 200) {
     
            const file = fs.createWriteStream(dest, { flags: 'wx' });
            file.on('finish', () => resolve());
            file.on('error', err => {
              file.close();
              if (err.code === 'EEXIST') reject('File already exists');
              else fs.unlink(dest, () => reject(err.message)); // Delete temp file
            });
            response.pipe(file);
          } else if (response.statusCode === 302 || response.statusCode === 301) {
            //Recursively follow redirects, only a 200 will resolve.
            download(response.headers.location, dest).then(() => resolve());
          } else {
            reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
          }
        });
    
        request.on('error', err => {
          reject(err.message);
        });
      });
    }
    

提交回复
热议问题