Get download progress in Node.js with request

前端 未结 6 2235
清酒与你
清酒与你 2020-12-02 15:27

I\'m creating an updater that downloads application files using the Node module request. How can I use chunk.length to estimate the remaining file

6条回答
  •  感动是毒
    2020-12-02 16:23

    If you are using "request" module and want to display downloading percentage without using any extra module, you can use the following code:

    function getInstallerFile (installerfileURL) {
    
        // Variable to save downloading progress
        var received_bytes = 0;
        var total_bytes = 0;
    
        var outStream = fs.createWriteStream(INSTALLER_FILE);
    
        request
            .get(installerfileURL)
                .on('error', function(err) {
                    console.log(err);
                })
                .on('response', function(data) {
                    total_bytes = parseInt(data.headers['content-length']);
                })
                .on('data', function(chunk) {
                    received_bytes += chunk.length;
                    showDownloadingProgress(received_bytes, total_bytes);
                })
                .pipe(outStream);
    };
    
    function showDownloadingProgress(received, total) {
        var percentage = ((received * 100) / total).toFixed(2);
        process.stdout.write((platform == 'win32') ? "\033[0G": "\r");
        process.stdout.write(percentage + "% | " + received + " bytes downloaded out of " + total + " bytes.");
    }
    

提交回复
热议问题