Skip to content

Instantly share code, notes, and snippets.

@nmccready
Created August 16, 2017 21:11
Show Gist options
  • Save nmccready/0b599569e3267553dbf250c382f45d16 to your computer and use it in GitHub Desktop.
Save nmccready/0b599569e3267553dbf250c382f45d16 to your computer and use it in GitHub Desktop.
reading directories files into a list
const fs = require('fs');
const Promise = require('bluebird');
const debug = require('../debug.js').spawn('readFiles');
const _ = require('lodash');
const readdirAsync = Promise.promisify(fs.readdir);
const readFileAsync = Promise.promisify(fs.readFile);
/**
* Easy way for us to load all files in a directory and index the content by the filename
*/
function readFiles(dirname) {
return readdirAsync(dirname)
.then((filenames) =>
Promise.map(filenames, (filename) =>
readFileAsync(dirname + '/' + filename, 'utf-8')
.then((content) => {
debug(() => filename);
debug(() => content);
return {filename, content}
})
))
.then((payload) => _(payload).keyBy("filename").mapValues('content').value());
}
module.exports = readFiles;
#!/usr/bin/env node
const readFiles = require('../util/readFiles.js');
const debug = require('../debug').spawn("script:readFiles");
const cwd = process.cwd();
debug("cwd: ", cwd);
debug("args:", process.argv);
debug();
debug("========================");
readFiles(`${cwd}/${process.argv[2]}`)
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment