utils-fs-read-dir

1.0.0 • Public • Published

Read Directory

NPM version Build Status Coverage Status Dependencies

Reads the contents of a directory.

Installation

$ npm install utils-fs-read-dir

Usage

var readdir = require( 'utils-fs-read-dir' );

readdir( path, clbk )

Reads the contents of a directory.

readdir( __dirname, onRead );
 
function onRead( error, data ) {
    if ( error ) {
        console.error( error );
    } else {
        console.log( data );
    }
}

readdir.sync( path )

Synchronously reads the contents of a directory.

var out = readdir.sync( __dirname );
if ( out instanceof Error ) {
    throw out;
}
console.log( out );

Notes

  • The difference between this module and fs.readdirSync() is that fs.readdirSync() will throw if an error is encountered (e.g., if given a non-existent path) and this module will return an error. Hence, the following anti-pattern

    var fs = require( 'fs' );
     
    var dir = '/path/to/dir';
     
    // Check for existence to prevent an error being thrown...
    if ( fs.existsSync( dir ) ) {
        dir = fs.readdirSync( dir );
    }

    can be replaced by an approach which addresses existence via error handling.

    var readdir = require( 'utils-fs-read-dir' );
     
    var dir = '/path/to/dir';
     
    // Explicitly handle the error...
    dir = readdir.sync( dir );
    if ( dir instanceof Error ) {
        // You choose what to do...
        throw dir;
    }

Examples

var readdir = require( 'utils-fs-read-dir' );
 
// Sync:
var out = readdir.sync( __dirname );
// returns <array>
 
console.log( out instanceof Error );
// returns false
 
out = readdir.sync( 'beepboop' );
// returns <error>
 
console.log( out instanceof Error );
// returns true
 
 
// Async:
readdir( __dirname, onRead );
readdir( 'beepboop', onRead );
 
function onRead( error, data ) {
    if ( error ) {
        if ( error.code === 'ENOENT' ) {
            console.error( 'Directory does not exist.' );
        } else {
            throw error;
        }
    } else {
        console.log( data );
    }
}

To run the example code from the top-level application directory,

$ node ./examples/index.js

Tests

Unit

Unit tests use the Mocha test framework with Chai assertions. To run the tests, execute the following command in the top-level application directory:

$ make test

All new feature development should have corresponding unit tests to validate correct functionality.

Test Coverage

This repository uses Istanbul as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:

$ make test-cov

Istanbul creates a ./reports/coverage directory. To access an HTML version of the report,

$ make view-cov

License

MIT license.

Copyright

Copyright © 2015. Athan Reines.

Package Sidebar

Install

npm i utils-fs-read-dir

Weekly Downloads

0

Version

1.0.0

License

MIT

Last publish

Collaborators

  • kgryte