2017-09-24 132 views
-1

我一直在試圖申請一個遞歸讀取目錄與FS模塊。我一路上都遇到過問題,它只給我一個文件名。以下是我需要它的方式:遞歸讀取目錄與文件夾

  • 文件名。
  • 還有該文件的目錄。 這個結果可能是作爲一個對象或被放入一個數組中。

請人幫忙。 謝謝。

+0

請告訴我們你有什麼到目前爲止已經試過 –

+0

_「並且還該文件的目錄」 _你已經有了這個,否則使用FS方法止跌不知道你想讀的是哪個目錄。如果您是指每個子目錄的路徑,那麼只要將每個子目錄名稱連接到路徑就可以了。但是如果沒有看到您的代碼,我們無法具體告訴您如何修復您的代碼。 –

回答

0

這裏是一個遞歸解決方案。您可以測試它,將它保存在一個文件中,運行node yourfile.js /the/path/to/traverse

const fs = require('fs'); 
const path = require('path'); 
const util = require('util'); 

const traverse = function(dir, result = []) { 

    // list files in directory and loop through 
    fs.readdirSync(dir).forEach((file) => { 

     // builds full path of file 
     const fPath = path.resolve(dir, file); 

     // prepare stats obj 
     const fileStats = { file, path: fPath }; 

     // is the file a directory ? 
     // if yes, traverse it also, if no just add it to the result 
     if (fs.statSync(fPath).isDirectory()) { 
      fileStats.type = 'dir'; 
      fileStats.files = []; 
      result.push(fileStats); 
      return traverse(fPath, fileStats.files) 
     } 

     fileStats.type = 'file'; 
     result.push(fileStats); 
    }); 
    return result; 
}; 

console.log(util.inspect(traverse(process.argv[2]), false, null)); 

輸出看起來是這樣的:

[ { file: 'index.js', 
    path: '/stackoverflow/test-class/index.js', 
    type: 'file' }, 
    { file: 'message.js', 
    path: '/stackoverflow/test-class/message.js', 
    type: 'file' }, 
    { file: 'somefolder', 
    path: '/stackoverflow/test-class/somefolder', 
    type: 'dir', 
    files: 
    [ { file: 'somefile.js', 
     path: '/stackoverflow/test-class/somefolder/somefile.js', 
     type: 'file' } ] }, 
    { file: 'test', 
    path: '/stackoverflow/test-class/test', 
    type: 'file' }, 
    { file: 'test.c', 
    path: '/stackoverflow/test-class/test.c', 
    type: 'file' } ] 
+0

它的工作原理!非常感謝。你是最棒的 –

相關問題