コマンドライン上でディレクトリとファイルをツリー表示にする
コンソール上でディレクトリとファイルをツリー表示するには以下のコードを実行します。
const fs = require('fs');
const path = require('path');
function printDirectoryTree(dir, indent = '') {
const items = fs.readdirSync(dir);
const directories = items.filter(item => fs.statSync(path.join(dir, item)).isDirectory());
const files = items.filter(item => !fs.statSync(path.join(dir, item)).isDirectory());
directories.forEach((item, index) => {
const fullPath = path.join(dir, item);
const isLastItem = index === directories.length - 1 && files.length === 0;
const prefix = isLastItem ? '└── ' : '├── ';
console.log(`${indent}${prefix}${item}/`);
const newIndent = indent + (isLastItem ? ' ' : '│ ');
printDirectoryTree(fullPath, newIndent);
});
files.forEach((item, index) => {
const isLastItem = index === files.length - 1;
const prefix = isLastItem ? '└── ' : '├── ';
console.log(`${indent}${prefix}${item}`);
});
}
const directoryPath = path.join(__dirname, './sample');
printDirectoryTree(directoryPath);
ディレクトリとファイルをツリー表示にする
Expressでulタグとliタグでディレクトリとファイルを階層表示するには以下のようにします。
scritp.js
const fs = require('fs');
const path = require('path');
function generateDirectoryTreeHTML(dir, level = 0) {
let html = ' '.repeat(level) + '<ul>\n';
const indent = ' '.repeat(level + 1); // インデントを調整
const items = fs.readdirSync(dir);
// ディレクトリとファイルを分けて取得
const directories = items.filter(item => fs.statSync(path.join(dir, item)).isDirectory());
const files = items.filter(item => !fs.statSync(path.join(dir, item)).isDirectory());
// ディレクトリを先に表示
directories.forEach(item => {
const fullPath = path.join(dir, item);
html += `${indent}<li class="dir">${item}/\n`;
html += generateDirectoryTreeHTML(fullPath, level + 2); // 再帰呼び出し
html += `${indent}</li>\n`;
});
// ファイルを後に表示し、aタグに相対パスを追加
files.forEach(item => {
const relativePath = path.relative(__dirname, path.join(dir, item));
html += `${indent}<li class="file"><a href="${relativePath}">${item}</a></li>\n`;
});
html += ' '.repeat(level) + '</ul>\n';
return html;
}
// 使用例
const directoryPath = path.join(__dirname, './sample');
const directoryTreeHTML = generateDirectoryTreeHTML(directoryPath);
let data = {"tree" : directoryTreeHTML};
res.render('node/tree', data)
CSSでファイルとディレクトリの画像を表示するには以下のようにCSSファイルを設定します。
.dir-file-box .dir {
background-image: url(./../images/dir.png);
background-repeat: no-repeat;
background-position: 0% 1px;
padding-left: 20px;
list-style: none;
margin: 4px 0;
}
.dir-file-box .file {
background-image: url(./../images/file.png);
background-repeat: no-repeat;
background-position: 0% 1px;
padding-left: 20px;
list-style: none;
margin: 4px 0;
}
ejsで表示するには、HTMLタグをエスケープせずにするため以下のようにします。
<div class="dir-file-box">
<%- tree %>
</div><!-- /div.dir-file-box -->