Readr

Flexible Node.js file reading library.

This project is maintained by benjreinhart

readr

Build Status

Flexible Node.js file reading library.

Readr is a library that abstracts reading files from disk. It supports recursively reading multiple files in a directory or reading an individual file via a clean API. It uses globber as its glob engine. Readr's API provides both sync and async operations.

What can readr do for you?

readr is a tool to read files and return a formatted object with the following properties:

It provides a nice abstraction around sync and async file reading, as well as reading individual files and globbing directories. It is compatible with node 0.8 upward.

Basic Example

Given the following directory tree:

/path/to/files/
  * some_directory/
    * file.txt
    * another_file.txt
    * csv_file.csv

And a current working directory of /path/to

find all .txt files

var readr = require('readr');
readr('files', {extension: 'txt'}, function(err, files) {
  console.log(files)
});
/*
  [
    {
      path: 'files/some_directory/file.txt',
      contents: 'Contents of file.txt',
      friendlyPath: 'files/some_directory/file'
    },
    {
      path: 'files/some_directory/another_file.txt',
      contents: 'Contents of another_file.txt',
      friendlyPath: 'files/some_directory/another_file'
    }
  ]
*/

Get a single file

readr('files/some_director/csv_file.csv', {friendlyPath: 'csv_file'}, function(err, files){
  console.log(files)
});
/*
  [
    {
      path: 'files/some_directory/csv_file.csv',
      contents: '',
      friendlyPath: 'files/some_directory/csv_file'
    }
  ]
*/

Or just get the paths and their corresponding friendlyPath of a directory

readr.getPaths('files', function(err, paths){
  console.log(paths)
});
/*
  [
    {path: 'files/some_directory/another_file.txt', friendlyPath: 'files/some_directory/another_file.txt'},
    {path: 'files/some_directory/csv_file.csv', friendlyPath: 'files/some_directory/csv_file.csv'},
    {path: 'files/some_directory/file.txt', friendlyPath: 'files/some_directory/file.txt'}
  ]
*/

What really makes readr powerful is its globbing engine, globber. For a much more comprehensive set of examples, see the test suite.

Installing

npm install readr

var readr = require('readr');

API

readr(path[, options], callback)

The path and options arguments are the same as the path and options arguments for globber (plus an additional friendlyPath and encoding option).

options can be the following:

Accepts all options globber accepts (except the includeDirectories option, which will always be false).

readr.sync(path[, options])

Synchronous version of readr.

readr.getPaths(path[, options], callback)

Similar to readr except it will not open and read the contents of the files found, rather it will just return the absolute path and (optionally) friendlyPath attribute of the files found.

readr.getPathsSync(path[, options])

Synchronous version of readr.getPaths.