2017-03-13 227 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

你能更新你的代碼實現來看看嗎? –