2017-09-09 73 views
0

我正在使用Node.js文件系統構建文件路徑數組。我想知道所有文件何時被讀取,所以我可以繼續使用我的數組。Node.js文件系統:Promise一次讀取所有文件

事件序列:

  1. 進入一個文件夾
  2. 獲取每個文件
  3. 將每個路徑到一個數組的路徑
  4. 讓我知道,一旦你完成

代碼:

'use strict'; 

const fs = require('fs'); 

function readDirectory(path) { 
    return new Promise((resolve, reject) => { 
    const files = []; 
    fs.readdir(path, (err, contents) => { 
     if (err) { 
     reject(err); 
     } 
     contents.forEach((file) => { 
     const pathname = `${ path }/${ file }`; 
     getFilesFromPath(pathname).then(() => { 
      console.log('pathname', pathname); 
      files.push(pathname); 
     }); 
     resolve(files); 
     }); 
    }); 
    }); 
} 

function getFilesFromPath(path) { 
    return new Promise((resolve, reject) => { 
    const stat = fs.statSync(path); 

    if (stat.isFile()) { 
     fs.readFile(path, 'utf8', (err, data) => { 
     if (err) { 
      reject(err); 
     } else { 
      resolve(data); 
     } 
     }); 
    } else if (stat.isDirectory()) { 
     readDirectory(path); 
    } 
    }); 
} 

getFilesFromPath('./dist'); 

將是巨大的用膠水:

Promise.all(files).then(() => { 
    // do stuff 
}) 

回答

2

你的建議非常作品 - 你嘗試了嗎?下面是做這件事的典型方式:

getFilesFromPath(path).then(files => { 
    const filePromises = files.map(readFile); 
    return Promises.all(filePromises); 
}).then(fileContentsArray => { 
    //do stuff - the array will contain the contents of each file 
}); 

你必須寫「READFILE()」函數自己,但看起來像你得到了覆蓋。

+0

謝謝鄧肯。我在看你的代碼,並試圖讓我的頭在這附近。因此,我的代碼構建了一個數組,但是使用'Promise.all(files).then(()=> {...});'我應該有一整套文件路徑,只要它們準備就緒。你能否詳細介紹一下映射位? – joe

+0

.map()調用將文件數組轉換爲文件內容承諾數組,然後我們調用該數組上的Promise.all()將其轉換爲單個Promise對象,該對象解決所有迷你承諾何時解決。大的承諾解決了一個數組。該數組包含每個個體承諾的所有解析值。見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all –

+0

我覺得我錯過了一些東西,因爲沒有任何東西被註銷: 'getFilesFromPath(' (文件)=> console.log('called'); })...' – joe