How to use Node.js to expand all nested folders and files in the file tree to generate a layer of full file paths All In One
How to use Node.js to expand all nested folders and files in the file tree to generate a layer of full file paths All In One
difficulty:
Medium
/ 难度:中等
solutions
如何使用 Node.js 把文件树中嵌套的文件夹和文件全部展开生成一层的文件全路径
import fs from 'node:fs';
import path from 'node:path';
const rootFolder = '/Users/xgqfrms-mm/Documents/github/IELTS-Guide-2th/docs/《雅思考试官方指南》(第2版)';
try {
let treeFilePath = rootFolder + `tree.md`;
if (!fs.existsSync(treeFilePath)) {
// do nothing
}
fs.writeFileSync(treeFilePath, ``, err => {
// init & clear
});
} catch (err) {
console.error(err);
}
const treeFlatRecursiveTraversal = async (folderName = rootFolder) => {
// console.log(`🚀 folderName =`, folderName);
await fs.readdirSync(folderName).map(fileName => {
// console.log(`❓ fileName =`, fileName);
const pathName = path.join(folderName, fileName);
fs.stat(pathName, async (err, stats) => {
// console.log(stats);
if(stats.isDirectory()) {
// console.log(`🗂️ folderName =`, fileName);
await treeFlatRecursiveTraversal(pathName)
} else {
// console.log(`📂 fileName =`, fileName)
const relativePath = pathName.replace(`/Users/xgqfrms-mm/Documents/github/IELTS-Guide-2th/docs/`, ``);
let url = `https://ielts-guide-2nd.xgqfrms.xyz/${encodeURIComponent(relativePath)}`;
switch (relativePath) {
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/01 Speaking Sample 1.mp4`:
url = `https://www.bilibili.com/video/BV1PbeueyEuE/`;
break;
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/02 Speaking Sample 2.mp4`:
url = `https://www.bilibili.com/video/BV15ueuetEKJ/`;
break;
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/03 Speaking Sample 3.mp4`:
url = `https://www.bilibili.com/video/BV1PbeueyEuE/`;
break;
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/04 Speaking Sample 4.mp4`:
url = `https://www.bilibili.com/video/BV1hVeueRE42/`;
break;
default:
// do nothing
break;
}
const aLink = `<a href="${url}" target="_blank">${relativePath}</a><br />\n`;
await fs.appendFile(rootFolder + `tree.md`, aLink, err => {
err && console.log(`err =`, err)
});
}
});
});
}
try {
await treeFlatRecursiveTraversal(rootFolder);
console.log(`treeFlatRecursiveTraversal ✅`)
} catch (err) {
console.error(`error ❌ =`, err);
}
fs & path
fs.readdirSync
fs.readdir
fs.readFile
.isDirectory
fs.existsSync
fs.writeFileSync
solutions
recursive
const treeGenerator = async (folderName = rootFolder) => {
await fs.readdirSync(folderName).map(fileName => {
// path
const pathName = path.join(folderName, fileName);
fs.stat(pathName, async (err, stats) => {
if(stats.isDirectory()) {
// console.log(`🗂️ folderName =`, fileName);
await treeGenerator(pathName)
} else {
// console.log(`📂 fileName =`, fileName)
const relativePath = pathName.replace(`/Users/xgqfrms-mm/Documents/github/IELTS-Guide-2th/docs/`, ``);
let url = `https://ielts-guide-2nd.xgqfrms.xyz/${encodeURIComponent(relativePath)}`;
const aLink = `<a href="${url}" target="_blank">${relativePath}</a><br />\n`;
await fs.appendFile(rootFolder + `tree.md`, aLink, err => {
//
});
}
});
});
}
demos
import fs from 'node:fs';
import path from 'node:path';
const rootFolder = '/Users/xgqfrms-mm/Documents/github/IELTS-Guide-2th/docs/《雅思考试官方指南》(第2版)';
try {
let treeFilePath = rootFolder + `tree.md`;
if (!fs.existsSync(treeFilePath)) {
// not useful
}
fs.writeFileSync(treeFilePath, ``, err => {
// init & clear
});
} catch (err) {
console.error(err);
}
// const isFile = fileName => {
// return fs.lstatSync(fileName).isFile() || false;
// };
// const isFolder = fileName => {
// return fs.lstatSync(fileName).isDirectory() || false;
// };
const results = [];
const treeGenerator = async (results = [], folderName = rootFolder) => {
// 读取文件夹
console.log(`🚀 folderName =`, folderName);
await fs.readdirSync(folderName).map(fileName => {
// console.log(`❓ fileName =`, fileName);
// path
const pathName = path.join(folderName, fileName);
// stat(pathName, (err, stats) => {
fs.stat(pathName, async (err, stats) => {
// console.log(stats);
// Stats {
// dev: 16777220,
// mode: 16877,
// nlink: 12,
// uid: 501,
// gid: 20,
// rdev: 0,
// blksize: 4096,
// ino: 64334171,
// size: 384,
// blocks: 0,
// atimeMs: 1723572008018.5503,
// mtimeMs: 1723572008013.725,
// ctimeMs: 1723572008013.725,
// birthtimeMs: 1723570190954.7646,
// atime: 2024-08-13T18:00:08.019Z,
// mtime: 2024-08-13T18:00:08.014Z,
// ctime: 2024-08-13T18:00:08.014Z,
// birthtime: 2024-08-13T17:29:50.955Z
// }
// console.log(stats.isDirectory());
if(stats.isDirectory()) {
// console.log(`🗂️ folderName =`, fileName);
await treeGenerator(results, pathName)
} else {
// console.log(`📂 fileName =`, fileName)
// const relativePath = encodeURIComponent(pathName.replace(`/Users/xgqfrms-mm/Documents/github/IELTS-Guide-2th/docs/`, ``));
const relativePath = pathName.replace(`/Users/xgqfrms-mm/Documents/github/IELTS-Guide-2th/docs/`, ``);
let url = `https://ielts-guide-2nd.xgqfrms.xyz/${encodeURIComponent(relativePath)}`;
switch (relativePath) {
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/01 Speaking Sample 1.mp4`:
url = `https://www.bilibili.com/video/BV1PbeueyEuE/`;
break;
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/02 Speaking Sample 2.mp4`:
url = `https://www.bilibili.com/video/BV15ueuetEKJ/`;
break;
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/03 Speaking Sample 3.mp4`:
url = `https://www.bilibili.com/video/BV1PbeueyEuE/`;
break;
case `《雅思考试官方指南》(第2版)/视频:口语考试实况录像/04 Speaking Sample 4.mp4`:
url = `https://www.bilibili.com/video/BV1hVeueRE42/`;
break;
// default:
// break;
}
const aLink = `<a href="${url}" target="_blank">${relativePath}</a><br />\n`;
//
await fs.appendFile(rootFolder + `tree.md`, aLink, err => {
//
});
// await fs.appendFile(rootFolder + `tree.md`, pathName + `\n`, err => {
// //
// });
results.push(pathName);
}
});
// if(isFolder(fileName)) {
// console.log(`🗂️ folderName =`, fileName)
// } else {
// console.log(`📂 fileName =`, fileName)
// }
// if(isFile(fileName)) {
// console.log(`📂 fileName =`, fileName)
// } else {
// console.log(`🗂️ folderName =`, fileName)
// }
// let temp = path.join(folderPath, fileName);
});
}
try {
await treeGenerator(results, rootFolder);
// console.log(`results =`, results);
} catch (err) {
console.error(`error ❌ =`, err);
}
https://ielts-guide-2nd.xgqfrms.xyz/
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
如何读取嵌套文件夹和文件以在 Node.js 中生成树结构 / How to read nested folders and files to generate a tree structure in Node.js
https://nodejs.org/en/learn/manipulating-files/working-with-folders-in-nodejs
https://dev.to/peaonunes/loading-a-directory-as-a-tree-structure-in-node-52bg
https://jakelunn.medium.com/simple-file-tree-electron-es6-71e8abc2c52
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/18370588
未经授权禁止转载,违者必究!