0

In my node application fs and gm to copy and conversion img file, How to check whether the copy and conversion particular stream is complete or not ?

ex: Img is picture url array.

for (var i = 0; i < Img.length; i++) {
    // copy img file , how to check this [i] img is copy complete
    fs.createReadStream('/' + Img[i]).pipe(fs.createWriteStream('/' + pngImg[i] + '_copy.png');

    gm('/' + Img[i].'_copy.png')
        .stream('jpg', function (err, stdout, stderr) {
            fs.createWriteStream('/' + Img[i].jpg);
            stdout.pipe(writeStream);
        });  // conversion img png to jpg , how to check this [i] img is conversion complete


    fs.unlink('/' + Img[i] + '_copy.png'), function (err) {
        console.log('successfully deleted');
    });
}

Or whether there is a better way? to complete copy, conversion and delete.

Finn
  • 1,323
  • 5
  • 24
  • 46

1 Answers1

0

If you make a copy of the original file only for the conversion, you don't need to do that. Your conversion can be straightforward:

var images = [
    'image1.png',
    'image2.png',
    'image3.png'
];

for (var i = 0; i < images.length; i++) {
    var file = images[i];
    var writeStream = fs.createWriteStream(__dirname + '/' + file + '.jpg');

    gm(__dirname + '/' + file)
        .stream('jpg')
        .pipe(writeStream)
        .on('finish', (function done(file) {
            console.log('done: ' + file);
        }).bind(null, file));
}
Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • I need the original file. Converting the original file will disappear. – Finn Dec 28 '15 at 10:57
  • thank! I try it, but I still want to know how to confirmed the action has been completed. – Finn Dec 29 '15 at 02:14
  • What is the function of this bind(null, file)? – Finn Dec 29 '15 at 02:56
  • The `.on('finish')` tells you when the conversion is done. I'm using `.bind(null, file)` to capture the file variable, if I don't do that, it will log `done: image3.png` 3 times ([question here](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example), the [answer with bind](http://stackoverflow.com/a/19323214/5388620)). – Shanoor Dec 29 '15 at 05:08
  • thank. In bind(null, file) function, what is the "null" parameter? how to using the parameter. – Finn Dec 30 '15 at 06:20
  • The [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). The first parameter is the `this` I'd have inside the `done()` function, I don't use `this` so I set it to null. The rest of the bind parameters are passed to the function (`file` for example), notice `function done(file)`. – Shanoor Dec 30 '15 at 07:45