Skip to content

Instantly share code, notes, and snippets.

@DaniGuardiola
Created June 26, 2017 15:45
Show Gist options
  • Save DaniGuardiola/da3115403f3415da46ac6b6058547309 to your computer and use it in GitHub Desktop.
Save DaniGuardiola/da3115403f3415da46ac6b6058547309 to your computer and use it in GitHub Desktop.
Generate CSV dir tree (node script)
// Generate CSV dir tree
const Promise = require('bluebird');
const fs = require('fs-promise');
const _ = require('lodash');
const path = require('path');
// install dependencies in script dir
// npm install bluebird fs-promise lodash
const DIR = '/home/dani/dir/to/scan'; // replace with target dir
// > node tree-to-csv.js > output.csv
const tree = (dir, preffix) => {
return Promise.resolve(fs.readdir(dir))
.then(files => filter(dir, files))
.then(files => Promise.mapSeries(files, (file, i) => readFile(dir, file, preffix, i + 1)))
.then(_.flattenDeep);
};
const filter = (dir, files) => Promise.map(files, (file) => {
return Promise.resolve(path.join(dir, file))
.then(fs.stat)
.then((s) => {
if (!s.isDirectory()) return false;
return file;
});
}).then(files => _.filter(files));
const readFile = (dir, file, preffix, count) => {
return Promise.resolve(path.join(dir, file))
.then(fs.stat)
.then((s) => {
const newPreffix = `${preffix ? `${preffix}.` : ''}${count++}`;
if (s.isDirectory()) {
return tree(path.join(dir, file), newPreffix).then(result => _.concat(`${newPreffix} ${file}`, result));
}
return false;
});
};
tree(DIR).then(dirs => `CARPETAS (${path.basename(DIR)})\n${dirs.join('\n')}`).tap(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment