Skip to content

Instantly share code, notes, and snippets.

@davidrleonard
Last active September 1, 2017 17:44
Show Gist options
  • Save davidrleonard/d3c747af976b45f78a5ebcbc37aecee7 to your computer and use it in GitHub Desktop.
Save davidrleonard/d3c747af976b45f78a5ebcbc37aecee7 to your computer and use it in GitHub Desktop.
Node utility functions for crawling files (for when you want to check a bunch of repos without bash)
/*
* Run in a directory with a bunch of subdirectories.
*
* Example: Get all subdirectories with names ending in '-design'
*
* ```
* const subdirs = getDirectories(__dirname).filter(isMatch.bind(null, /\-design$/));
* ```
*
* Example: Get all subdirectories that have any subfiles named *.es6.js
*
* ```
* const hasES6File = source => getFiles(source).filter(isMatch.bind(null, /\.es6\.js$/)).length > 0;
* const dirsWithES6 = getDirectories(__dirname).filter(hasES6File);
* ```
*
* Thanks to https://stackoverflow.com/questions/18112204/get-all-directories-within-directory-nodejs
* for many of the methods below.
*/
const fs = require('fs');
const path = require('path');
const isDirectory = source => fs.lstatSync(source).isDirectory();
const isFile = source => fs.lstatSync(source).isFile();
const isMatch = (regex, source) => regex.test(source);
const getDirectories = source =>
fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
const getFiles = source =>
fs.readdirSync(source).map(name => path.join(source, name)).filter(isFile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment