4

I recently asked/accepted an answer to a question I had earlier: How can I replicate the functionality of a wget with nodejs.

Now, my script is functioning perfectly, but I'd like to be able to show the user the percentage that's downloaded. I'm not sure if that's exposed to us (I didn't see it in the docs), but I figured I'd ask here anyways. Would love some help!

Thanks!

Community
  • 1
  • 1
Connor
  • 4,138
  • 8
  • 34
  • 51

1 Answers1

8

Yes, you can. With child_process.spawn. While child_process.exec executes the command and buffers the output, spawn gives you events on data, error and end. So you can listen to that and calculate your progress. There's a basic example in the node docs for spawn.

Update: I saw your other question. You can use wget for this, but I recommend the nodejs module request instead. Here's how to fetch the file with request:

var request = require("request");

request(url, function(err, res, body) {
  // Do funky stuff with body
});

If you want to track progress, you pass a callback to onResponse:

function trackProgress(err, res) {
  if(err)
    return console.error(err);

  var contentLength = parseInt(res.headers["content-length"], 10),
      received = 0, progress = 0;
  res.on("data", function(data) {
    received += data.length;
    progress = received / contentLength;
    // Do funky stuff with progress
  });
}

request({url: url, onResponse: trackProgress}, function(err, res, body) {
  // Do funky stuff with body
});
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
  • you are saying " spawn gives you events on data, error and end ". So is it possible to get the progress of a python script execution with spawn ? If yes, can you answer this question please ? http://stackoverflow.com/questions/33802895/show-progressbar-of-python-script-execution-with-nodejs – AshBringer Dec 21 '15 at 19:15