Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-formidable and a simple progress bar

Tags:

node.js

If I look into the node-formidable documentation I can read:

"Event: 'progress' (bytesReceived, bytesExpected)
Emitted after each incoming chunk of data that has been parsed. 
Can be used to roll your    own progress bar."

I am wondering how to implement my own progress bar I mean how to read that information client side? I am quite confused. Is it implemented with a polling GET that starts after the POST has started or is it possible to read the information from the POST request while uploading?

If I look at this:

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(sys.inspect({fields: fields, files: files}));
    });
    return;
  }

Look like the /upload url is handling the POST request and returning something res.write('received upload:\n\n');

My question is who can read that

res.write('received upload:\n\n');
like image 379
Liborio Francesco Cannici Avatar asked Mar 16 '11 09:03

Liborio Francesco Cannici


People also ask

What is node formidable?

Formidable is a Node. js module for parsing form data, especially file uploads.


2 Answers

You don't need to override the onPart hook!

Just broadcast a message though socket at every form progress event callback call like this:

form.on('progress', function(bytesReceived, bytesExpected) {
  var progress = {
    type: 'progress',
    bytesReceived: bytesReceived,
    bytesExpected: bytesExpected
  };

  socket.broadcast(JSON.stringify(progress));
});

than on client listen for socket messages.

like image 188
Giovanni Cappellotto Avatar answered Nov 03 '22 00:11

Giovanni Cappellotto


A good options could be using socket.io

Remember to overwrite the onPart hook.

incomingForm.onPart = function(part) {
  part.addListener('data', function() {
    // send back to the client the status
  });
}
like image 45
masylum Avatar answered Nov 03 '22 02:11

masylum