Handling Streams


#1

I wondered if someone could give me some pointers as to whether what I’m doing here is correct.

Basically I’m extracting files from a rar using the npm unrar. It returns a stream that I then process by pipeing it out to a file. That pipeing is done asynchronously, but I don’t know how best to capture when it is finished. I’ve resorted to incrementing a counter when the writable file is opened and decrementing it when it is closed. Then once all the files are closed and the counter is zero I can call the next process.

var unrar = require('unrar'),
    rar = new unrar(rarFile);

rar.list((err, entries) => {
    entries.sort((a, b) => {
        if (path.basename(a.name) < path.basename(b.name)) {
            return -1;
        } else {
            return 1;
        }
    });

    var active = 0;
    for (var i=0; i<entries.length; i++) {
        console.log(i, path.basename(entries[i].name));

        var stream = rar.stream(entries[i].name),
            writeable = fs.createWriteStream(path.join(tmpPath, path.basename(entries[i].name)));
        stream.on('error', (err) => {
            console.error(err);
        });
        writeable.on('open', () => {
            console.log('writeable open');
            active++;
        });
        writeable.on('close', () => {
            console.log('writeable close');
            active--;
            if (active == 0) {
                console.log('all done!');
            }
        });
        stream.pipe(writeable);
    }

});

Grateful for your thoughts and suggestions where I can learn more from.