Last active
May 25, 2020 20:33
-
-
Save goliney/e0fc15d1947a54b6c27dfe0ccb4962fc to your computer and use it in GitHub Desktop.
Get list of files and directories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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