Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8829

【Node.js】複数のファイルパスをオブジェクトでの階層表現に変換する

$
0
0

経緯

Node.jsのfsを使って特定のディレクトリの中身をファイルパスにて取得した際に、ディレクトリの階層と互換性のあるオブジェクトに変換したかった。

結論

index.js
constdata=['/public/aaa/1.file','/public/aaa/2.file','/public/bbb/1.file','/public/ccc/1.file','/public/ccc/2.file','/public/ccc/3.file','/public/ddd/1.file'];constoutput={};letcurrent;for(constpathofdata){current=output;for(constsegmentofpath.split('/')){if(segment!==''){if(!(segmentincurrent)){current[segment]={};}current=current[segment];}}}console.log(output);/* 実行結果
{ public:
   { 
     aaa: { '1.file': {}, '2.file': {} },
     bbb: { '1.file': {} },
     ccc: { '1.file': {}, '2.file': {}, '3.file': {} },
     ddd: { '1.file': {} } 
   } 
}
*/

あとは取得した結果から

子要素に値が入っていたらディレクトリ
子要素に値が入っていなかったらファイル

と認識して分岐させれば色々使えると思う。


Viewing all articles
Browse latest Browse all 8829

Trending Articles