Created
June 26, 2017 15:45
-
-
Save DaniGuardiola/da3115403f3415da46ac6b6058547309 to your computer and use it in GitHub Desktop.
Generate CSV dir tree (node script)
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
// 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