[ACCEPTED]-Upload Progress — Request-coffeescript

Accepted answer
Score: 14

I spent a couple of hours to find anything 8 valid in request and node sources, and finally found 7 a different approach, which feels more correct 6 to me.

We can rely on drain event and bytesWritten property:

request.put({
  url: 'https://example.org/api/upload',
  body: fs.createReadStream(path)
}).on('drain', () => {
  console.log(req.req.connection.bytesWritten);
});

Alternatively 5 if you need to handle progress of file bytes, it's 4 easier to use stream data event:

let size = fs.lstatSync(path).size;
let bytes = 0;

request.put({
  url: 'https://example.org/api/upload',
  body: fs.createReadStream(path).on('data', (chunk) => {
    console.log(bytes += chunk.length, size);
  })
});

Stream buffer 3 size is 65536 bytes and read/drain procedure 2 runs iteratively.

This seems to be working 1 pretty well for me with node v4.5.0 and request v2.74.0.

Score: 11

I needed a handle on the upload progress 3 for yet another project of mine.

What I found 2 out is that you can poll the request's connection._bytesDispatched property.

For 1 example:

r = request.post url: "http://foo.com", body: fileAsBuffer
setInterval (-> console.log "Uploaded: #{r.req.connection._bytesDispatched}"), 250

Note: If you were piping to r, poll r.req.connection.socket._bytesDispatched instead.

Score: 3
var request = require('request');
    var fs = require('fs');  
    let path ="C:/path/to/file";
    var formData = {
        vyapardb: fs.createReadStream(path)
    };

    let size = fs.lstatSync(path).size;

    var headers = {
        'Accept' : 'application/json',
        'Authorization' : 'Bearer '+token,
    };

    var r = request.post({url:'http://35.12.13/file/upload', formData: formData,  headers: headers}, function optionalCallback(err, httpResponse, body) {
        clearInterval(q);

    });
    var q = setInterval(function () {
        var dispatched = r.req.connection._bytesDispatched;
        let percent = dispatched*100/size;
         console.dir("Uploaded: " + percent + "%");

    }, 250);
}

0

Score: 1

I know this is old, but I just found a library 4 'progress-stream' that has not been mentioned 3 and does this very nicely. https://www.npmjs.com/package/progress-stream

const streamProg = require('progress-stream');
const fs = require('fs');
const request = require('request');

const myFile = 'path/to/file.txt';
const fileSize = fs.statSync('path/to/file.txt').size;
const readStream = fs.createReadStream(myFile);
const progress = streamProg({time: 1000, length: fileSize})
    .on('progress', state => console.log(state));

readStream.pipe(progress).pipe(request.put({url: 'SOMEURL/file.txt'}));

Similarly, it 2 can be used between a pipe on download as 1 well.

More Related questions