2017-03-13 314 views
2

我正在编写一个节点js函数,它将文件解压缩并进一步读取解压缩的文件以进一步处理。问题是,在文件异步解压缩之前,读取函数会启动并且会失败,并显示找不到文件错误。请在读取文件触发器之前建议可能的方法来等待解压缩过程。等待异步方法完成

回答

0

感谢答案,我已经得到它与以下代码 -

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

到这里看看:

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

节点英雄 - 了解异步编程中的Node.js

这是本系列教程的后第三称为节点英雄 - 在这些章节中,您可以学习如何开始使用Node.js并使用它来交付软件产品。

在本章中,我将指导您完成异步编程原则,并向您展示如何在JavaScript和Node.js中执行异步操作。

+0

谢谢@EAK TEAM – geekintown

+0

如果您觉得有用,请标记为答复或请注意 –

0

异步库(http://caolan.github.io/async/

这个库是为了控制你的功能execusion使用。

例如:

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(...); 
}); 

这里一旦解压任务调用回调funcion readingUnzipFiles执行。

Promisses

另一个解决方案是使用像Q上promisse模块(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; 
} 

然后,你可以使用的功能,如:

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

.Thanks。我的解压缩函数将许多文件写入文件系统,并且我想只在所有文件写入后才读取它们。上面的例子可以解决这个问题吗? – geekintown

+0

我正在使用fs.writeFile()函数来编写每个文件。是他们在写入所有文件时获得回调的一种方式。谢谢 – geekintown

+0

你能更新你的代码实现来看看吗? –