geekintown
geekintown

Reputation: 119

Wait for an async method to finish

i am writing a node js function which unzip a file and further read the unzipped files to process further. The problem is, before the file gets unzipped asynchronously, the read function gets started and it fails with file not found error. please suggest possible way to wait for unzip process before read file triggers.

Upvotes: 3

Views: 3118

Answers (3)

geekintown
geekintown

Reputation: 119

Thanks for the answers, i have got it working with following code -

fs.createReadStream('master.zip')
.pipe(unzip.Extract({ path: 'gitdownloads/repo' }))
.on('close', function () {
...
});

Upvotes: 1

Cristian Colorado
Cristian Colorado

Reputation: 2040

Async library(http://caolan.github.io/async/)

This library is used in order to control the execusion of the functions you have.

For example:

async.series({
    unzip: function(callback) {
        unzip('package.zip', function(err, data) {
            if(!err)
               callback(null, data);
        });
    }
}, function(err, results) {
    // results is now equal to: {unzip: data}
    readingUnzipFiles(...);
});

Here readingUnzipFiles is executed once the unzip task calls the callback funcion.

Promisses

Another solution would be use a promisse module like Q(https://github.com/kriskowal/q):

function unzip(fileName, outputPath) {
    var deferred = Q.defer();

    fs.createReadStream(fileName)
       .pipe(unzip.Extract({ path: outputPath }))
       .on('end', function(){
           deferred.resolve(result);
       });

    return deferred.promise;
}

Then you could use the function like:

unzip('file.zip', '/output').then(function() {
    processZipFiles();
});

Upvotes: 0

EAK TEAM
EAK TEAM

Reputation: 7492

Take a look here :

https://blog.risingstack.com/node-hero-async-programming-in-node-js/

Node Hero - Understanding Async Programming in Node.js

This is the third post of the tutorial series called Node Hero - in these chapters you can learn how to get started with Node.js and deliver software products using it.

In this chapter, I’ll guide you through async programming principles, and show you how to do async in JavaScript and Node.js.

Upvotes: 2

Related Questions