Getting a progress for an FTP-upload with node

5.3k Views Asked by At

I have an Electron app which uploads a dropped file to a predefined server with node-ftp. The upload works like a charm, but despite reading a couple of suggestions I cannot figure out how to get information on the actual progress for a progress-bar. My upload-code so far:

var ftp = new Client();
let uploadfile = fs.createReadStream(f.path);
let newname = uuid(); //some function I use for renaming

ftp.on('ready', function () {
    ftp.put(uploadfile, newname, function (err) {
        if (err) throw err;
        ftp.end();
    });
});

c.connect({user: 'test', password: 'test'});

I always stumble across monitoring the 'data' event, but could not find out how or where to access it (as you can see I'm quite new to JavaScript).

2

There are 2 best solutions below

1
On BEST ANSWER

Got it. I found the answer in streams with percentage complete

With my code changed to

var ftp = new Client();
let uploadfile = fs.createReadStream(f.path);
let newname = uuid(); //some function I use for renaming

ftp.on('ready', function() {
    uploadfile.on('data', function(buffer) {
        var segmentLength = buffer.length;
        uploadedSize += segmentLength;
        console.log("Progress:\t" + ((uploadedSize/f.size*100).toFixed(2) + "%"));
    });

    ftp.put(uploadfile, newname, function(err) {
        if (err) throw err;
            ftp.end();
    });
});
c.connect({user: 'test', password: 'test'});

I get the percentage uploaded in console. From here it's only a small step to a graphical output.

1
On

on client side you can create a byte count for your upload stream (http://www.experts.exchange.com/questions/24041115/upload-file-on-ftp-with-progressbar-and-time-left.html)

  • set lower limit of the progressbar to 0
  • set upper limit to file length of upload file
  • feed the progress bar with the byte count

(http://www.stackoverflow.com/questions/24608048/how-do-i-count-bytecount-in-read-method-of-inputstream)

maybe you can use npm like stream-meter (https://www.npmjs.com/package/stream-meter) or progress-stream (https://www.npmjs.com/package/progress-stream) and pipe your file stream through to feed the progressbar. i am not sure about that because i do not know the internals of the npms. in progress-stream is a function transferred() that would fit exactly

a very accurate way is to have code on the server that gives feedback to the browser (http://www.stackoverflow.com/questions/8480240/progress-bar-for-iframe-uploads)