2013-08-19 21 views
19

Tworzę aktualizator, który pobiera pliki aplikacji przy użyciu modułu węzła request. Jak mogę użyć wartości chunk.length do oszacowania pozostałego rozmiaru pliku? Oto część mojego kodu:Pobierz postęp w pliku Node.js z żądaniem

var file_url = 'http://foo.com/bar.zip'; 
var out = fs.createWriteStream('baz.zip'); 

var req = request({ 
    method: 'GET', 
    uri: file_url 
}); 

req.pipe(out); 

req.on('data', function (chunk) { 
    console.log(chunk.length); 
}); 

req.on('end', function() { 
    //Do something 
}); 
+0

mam wewnątrz .zip: node-webkit.app/a kiedy wyodrębniam dane-> NIE MOŻNA uruchomić .app już:/mój kod :: fs.writeFileSync (frameZipFilePath, dane, "binary"); var zip = new AdmZip (frameZipFilePath); zip.extractAllTo (ścieżka.resolve ("", "tmp"), prawda); – miukki

Odpowiedz

18

To powinno Ci sumę chcesz:

req.on('response', function (data) { 
    console.log(data.headers[ 'content-length' ]); 
}); 

dostaję długość treści o 9404541

+0

Dzięki! Czy to długość w bajtach? – Harangue

+2

@ J4G Powinno tak być, tak: http://stackoverflow.com/a/2773408. –

15
function download(url, callback, encoding){ 
     var request = http.get(url, function(response) { 
      if (encoding){ 
       response.setEncoding(encoding); 
      } 
      var len = parseInt(response.headers['content-length'], 10); 
      var body = ""; 
      var cur = 0; 
      var obj = document.getElementById('js-progress'); 
      var total = len/1048576; //1048576 - bytes in 1Megabyte 

      response.on("data", function(chunk) { 
       body += chunk; 
       cur += chunk.length; 
       obj.innerHTML = "Downloading " + (100.0 * cur/len).toFixed(2) + "% " + (cur/1048576).toFixed(2) + " mb\r" + ".<br/> Total size: " + total.toFixed(2) + " mb"; 
      }); 

      response.on("end", function() { 
       callback(body); 
       obj.innerHTML = "Downloading complete"; 
      }); 

      request.on("error", function(e){ 
       console.log("Error: " + e.message); 
      }); 

     }); 
    }; 
+1

Skąd pochodzi '1048576'? Czy to jest kosmiczna stała? – Sukima

+0

Mniejsza o liczbę bajtów w Mega-Bajcie. – Sukima

+1

https://www.google.ru/search?q=bytes+in+mega-Byte&oq=bytes+in+mega-Byte&aqs=chrome..69i57.1633j0j7&sourceid=chrome&espv=210&es_sm=91&ie=UTF- 8 – miukki

2

Napisałem moduł, który właśnie robi czego chcesz: status-bar.

var bar = statusBar.create ({ total: res.headers["content-length"] }) 
    .on ("render", function (stats){ 
     websockets.send (stats); 
    }) 

req.pipe (bar); 
+0

Tak, początkowo użyłem twojego modułu, ale chciałem móc wyświetlić pasek postępu dla użytkownika w GUI z websockets. – Harangue

+0

Możesz to zrobić. Gdy wywoływana jest funkcja render, wyślij do klienta pasek stanu. To jest łańcuch, możesz z nim wszystko zrobić. –

+0

Dobrze, ale w pewnym momencie łatwiej jest napisać coś samemu niż sparsować ciąg innego modułu. :) Docenić napiwek. – Harangue

6

Korzystanie z modułu chłodzenia node-request-progress, można zrobić coś takiego w es2015:

import { createWriteStream } from 'fs' 
import request from 'request' 
import progress from 'request-progress' 

progress(request('http://foo.com/bar.zip')) 
.on('progress', state => { 

    console.log(state) 

    /* 
    { 
     percentage: 0.5,  // Overall percentage (between 0 to 1) 
     speed: 554732,   // The download speed in bytes/sec 
     size: { 
     total: 90044871,  // The total payload size in bytes 
     transferred: 27610959 // The transferred payload size in bytes 
     }, 
     time: { 
     elapsed: 36.235,  // The total elapsed seconds since the start (3 decimals) 
     remaining: 81.403  // The remaining seconds to finish (3 decimals) 
     } 
    } 
    */ 

    }) 
    .on('error', err => console.log(err)) 
    .on('end',() => {}) 
    .pipe(createWriteStream('bar.zip')) 
1

W przypadku gdy ktoś chce wiedzieć postępy bez użycia innej biblioteki, ale tylko wniosek, wówczas można użyj następującej metody:

function downloadFile(file_url , targetPath){ 
    // Save variable to know progress 
    var received_bytes = 0; 
    var total_bytes = 0; 

    var req = request({ 
     method: 'GET', 
     uri: file_url 
    }); 

    var out = fs.createWriteStream(targetPath); 
    req.pipe(out); 

    req.on('response', function (data) { 
     // Change the total bytes value to get progress later. 
     total_bytes = parseInt(data.headers['content-length' ]); 
    }); 

    req.on('data', function(chunk) { 
     // Update the received bytes 
     received_bytes += chunk.length; 

     showProgress(received_bytes, total_bytes); 
    }); 

    req.on('end', function() { 
     alert("File succesfully downloaded"); 
    }); 
} 

function showProgress(received,total){ 
    var percentage = (received * 100)/total; 
    console.log(percentage + "% | " + received + " bytes out of " + total + " bytes."); 
    // 50% | 50000 bytes received out of 100000 bytes. 
} 

downloadFile("https://static.pexels.com/photos/36487/above-adventure-aerial-air.jpg","c:/path/to/local-image.jpg"); 

zmienna received_bytes zapisuje sumie każdego wysłanego długości bryłkach i zgodnie z total_bytes, pro gress jest retrieven.

1

Jeśli używasz „żądanie” moduł i chcesz wyświetlać pobierania odsetek bez stosowania żadnego dodatkowego modułu, można użyć następującego kodu:

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."); 
}