Skip to content

Instantly share code, notes, and snippets.

@goliney
Last active May 25, 2020 20:33
Show Gist options
  • Save goliney/e0fc15d1947a54b6c27dfe0ccb4962fc to your computer and use it in GitHub Desktop.
Save goliney/e0fc15d1947a54b6c27dfe0ccb4962fc to your computer and use it in GitHub Desktop.
Get list of files and directories
const path = require('path');
const fs = require('fs');
/*
Possible usage:
node listFiles.js >> files.json
Don't forget to edit rootDirPath first.
*/
const rootDirPath = path.join(__dirname, 'dist');
const files = listNodes(rootDirPath);
console.log(JSON.stringify({ files }, null, 2));
function listNodes(nodePath, root) {
const relativeRoot = root || nodePath;
try {
const nodes = fs.readdirSync(nodePath);
const currentNode = [
{
isDir: true,
path: nodePath,
relativePath: path.relative(relativeRoot, nodePath),
},
];
if (nodes.length === 0) {
return currentNode;
}
// recursively get child nodes
const subNodes = nodes.map(nodeName => listNodes(path.join(nodePath, nodeName), relativeRoot));
return subNodes.reduce((acc, val) => acc.concat(val), currentNode);
} catch (err) {
if (err.code === 'ENOTDIR') {
return [
{
isDir: false,
path: nodePath,
relativePath: path.relative(relativeRoot, nodePath),
},
];
}
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment