Created
March 25, 2016 18:08
-
-
Save Cl3MM/1a7aaafe1fdcd43ccd1b to your computer and use it in GitHub Desktop.
Node recursive file lister
This file contains 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
// npm i walk --save | |
var walk = require('walk'), | |
fs = require('fs'), | |
path = require('path'), | |
util = require('util'); | |
// We will list the content of the upper directory from where we are | |
var ROOT_PATH = path.normalize(path.join(__dirname, '../')); | |
// let's walk the path... | |
var walker = walk.walk(ROOT_PATH, { | |
followLinks: false, | |
filters: ["node_modules", 'pluralsight'] | |
}) | |
// Our resulting files object | |
var FILES = {} | |
// this method will create nested properties if the object does not have it, and push a value to an array: | |
// obj = {} | |
// keyPath = ['a', 'b', 'c'] | |
// value = 'xxx' | |
// assign(obj, keyPath, value) => {a: b: c: ['xxx']} | |
// see http://stackoverflow.com/questions/5484673/javascript-how-to-dynamically-create-nested-objects-using-object-names-given-by | |
var assign = function(obj, keyPath, value) { | |
lastKeyIndex = keyPath.length-1; | |
for (var i = 0; i < lastKeyIndex; ++ i) { | |
key = keyPath[i]; | |
if (!(key in obj)) | |
obj[key] = {} | |
obj = obj[key]; | |
} | |
if(obj[keyPath[lastKeyIndex]]) | |
obj[keyPath[lastKeyIndex]].push(value); | |
else | |
obj[keyPath[lastKeyIndex]] = [value]; | |
} | |
var log = function(obj) { | |
console.log(util.inspect(obj, false, null)); | |
} | |
var fileHandler = function(root, stat, next) { | |
var path = root.replace(ROOT_PATH, "/root").replace(/\\/g, '/').split('/') | |
path.shift() | |
assign(FILES, path, stat.name) | |
next(); | |
} | |
function endHandler() { | |
console.log("all done"); | |
log(FILES); | |
} | |
walker.on("file", fileHandler); | |
walker.on("end", endHandler); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment