2017-05-18 70 views
0

在node.js中,我有一個通過文件夾循環的模塊。實際上有一個函數回調,當它從目錄讀完時觸發。然而,對於它找到的每個文件,我運行一個readFile命令,它是異步函數,讀取文件,並且具有回調函數。問題是,如何設置它,以便在目錄循環功能完成時有回調,並且還有每個readFile函數?如何在一系列readFile調用在node.js中完成時運行函數?

var klaw = require('klaw'); 
var fse = require('fs-extra'); 

var items = []; 

klaw("items").on('data', function (item) { 
    var dir = item.path.indexOf(".") == -1; 
    // if its a file 
    if (!dir) { 
     var filename = item.path; 
     if (filename.toLowerCase().endsWith(".json")) { 
      fse.readFile(filename, function(err, data) { 
       if (err) return console.error(err); 
       items.push(JSON.parse(data.toString())); 
      }); 
     } 
    } 
}).on('end', function() { 

}); 

回答

1

嘗試這樣的事情

import Promise from 'Bluebird'; 

    const processing = [] 
    const items = []; 

    klaw("items") 
    .on('data', item => processing.push(
     Promise.promisify(fs.readFile))(item.path) 
     .then(content => items.push(JSON.parse(content.toString()))) 
     .catch(err => null) 
    ) 
    .on('end',() => { 
     Promise.all(processing) 
     .then(nothing => console.log(items)) 
    }) 

或類似

const processing = [] 

klaw("items") 
.on(
    'data', 
    item => processing.push(Promise.promisify(fs.readFile)(item.path)) 
) 
.on(
    'end', 
() => { 
    Promise.all(processing) 
    .then(contents => (
     contents.map(content =>(JSON.parse(content.toString()))) 
    ) 
    .then(items => console.log(items)) 

}) 
+0

Promise.promisify未定義 – omega

+0

你必須輸入藍鳥 –

+0

你怎麼可以修改代碼,因此它不包括文件夾?我在上面的代碼中檢查過。 – omega

相關問題