npm stats
  • Search
  • About
  • Repo
  • Sponsor
  • more
    • Search
    • About
    • Repo
    • Sponsor

Made by Antonio Ramirez

filter-files

0.4.0

@jonschlinkert

npmHomeRepoSnykSocket
Downloads:137605
$ npm install filter-files
DailyWeeklyMonthlyYearly

filter-files NPM version

Recursively read directories and return a list of files, filtered to have only the files for which the (optional) filter function returns true. Sync and async.

Install

Install with npm

npm i filter-files --save

Run tests

npm test

Usage

var filter = require('filter-files');

sync

filter.sync(dir, [recurse], [filterFn]);

Params

  • dir {String}: the directory to start from. Returns all files, recursively, starting with this path.
  • filterFn {Function}: optionally pass a filter function to use for filtering files/dirs. This function filters "on the fly", so recursion is very fast.
  • recurse {Boolean}: pass false to disable recursion.

Examples

var files = filter.sync('lib');
console.log(files);
//=> [ 'lib/async.js', 'lib/filter.js', 'lib/sync.js' ]

Pass a filter function:

filter.sync('lib', function(fp) {
  return /a/.test(fp);
});
//=> [ 'lib/async.js' ]

Or an array of filter functions:

function include(fp) {
  return /^\./.test(fp);
}
function exclude(fp) {
  return !/^\.[jntv]/.test(fp);
}

// pass `false` to prevent recursion
filter('.', [include, exclude], false);
//=> ['.git', '.gitignore', '.gitattribuets']

async

filter(dir, [recurse], [filterFn], callback));

Params

Same as sync with the addition of callback.

Examples

filter('lib', function(err, files) {
  console.log(files);
  //=> [ 'lib/async.js', 'lib/filter.js', 'lib/sync.js' ]
});

Pass a filter function:

var fn = function(fp) {
  return /a/.test(fp);
};

filter('lib', fn, function(err, files) {
  console.log(files);
  //=> [ 'lib/async.js' ]
});

Filtering

Filter functions take four parameters and return true or false.

Params

  • fp filepath being looped over
  • dir current directory
  • files accumulated array of files
  • recurse whether recurse is true or false

Example

This function returns a filter function for getting files with the given extname:

var path = require('path');
var isDir = require('is-directory');

function ext(extname) {
  // this is our filter function
  return function filter(fp, dir, files, recurse) {
    if (isDir(path.join(dir, fp)) && recurse === true) {
      return true;
    }
    return path.extname(fp) === extname;
  }
}

See the tests for more examples.

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Author

Jon Schlinkert

  • github/jonschlinkert
  • twitter/jonschlinkert

License

Copyright (c) 2014 Jon Schlinkert
Released under the MIT license


This file was generated by verb on November 17, 2014.