How to use Node.js to get all files full paths that nested in folders All In One
如何使用 Node.js 获取文件夹中嵌套的所有文件的完整路径
demos
ESM
// ❌
// import fs from 'node:fs/promises';
// ✅
import * as fs from 'node:fs/promises';
// import * as fs from 'node:fs';
import * as path from 'node:path';
async function main() {
async function findFiles(folderName, arr = []) {
let result = arr || [];
const items = await fs.readdir(folderName, { withFileTypes: true });
// ✅ fix
for (const item of items) {
const name = path.join(folderName, item.name);
if (path.extname(item.name) === ".json") {
// file
console.log(`Found file: ${item.name} in folder: ${folderName}`);
result.push(name);
} else {
// folder
await findFiles(name, result);
}
}
return result;
}
const files = await findFiles("stores");
console.log(`❓files =`, files);
}
main();
/*
$ node ./bug-fix.esm
Found file: sales.json in folder: stores/201
Found file: sales.json in folder: stores/202
Found file: data.json in folder: stores/2022/11/11
❓files = [
'stores/201/sales.json',
'stores/202/sales.json',
'stores/2022/11/11/data.json',
]
*/
CJS
const fs = require("fs").promises;
const path = require("path");
async function main() {
async function findFiles(folderName, arr = []) {
let result = arr || [];
const items = await fs.readdir(folderName, { withFileTypes: true });
// ✅ fix
for (const item of items) {
const name = path.join(folderName, item.name);
if (path.extname(item.name) === ".json") {
// file
console.log(`Found file: ${item.name} in folder: ${folderName}`);
result.push(name);
} else {
// folder
await findFiles(name, result);
}
}
return result;
}
const files = await findFiles("stores");
console.log(`❓files =`, files);
}
main();
/*
$ node ./bug-fix.cjs
Found file: sales.json in folder: stores/201
Found file: sales.json in folder: stores/202
Found file: data.json in folder: stores/2022/11/11
❓files = [
'stores/201/sales.json',
'stores/202/sales.json',
'stores/2022/11/11/data.json',
]
*/
https://gitlab.com/webgeeker/node.js-file-system/-/blob/main/bug-fix.js?ref_type=heads
https://gitlab.com/webgeeker/node.js-file-system/-/tree/main?ref_type=heads