Learn about our RFC process, Open RFC meetings & more.Join in the discussion! »

read-multiple-files

2.0.0-4 • Public • Published

read-multiple-files

npm version Build Status Build status Coverage Status

A Node.js module to read multiple files asynchronously

const readMultipleFiles = require('read-multiple-files');
 
readMultipleFiles(new Set(['one.txt', 'another.txt']), (err, bufs) => {
  if (err) {
    throw err;
  }
 
  bufs; //=> [<Buffer ... >, <Buffer ... >]
});

Installation

Use npm.

npm install read-multiple-files

API

const readMultipleFiles = require('read-multiple-files');

readMultipleFiles(paths [, options], callback)

paths: <Array|Set<string|Buffer|URL|integer>> (file paths)
options: Object ([fs.readFile] options) or string (encoding)
callback: Function

callback(error, contents)

error: Error if it fails to read at least one of the files, otherwise null
contents: Array<Buffer> or Array<string> (according to encoding option)

The second argument will be an array of file contents. The order of contents follows the order of file paths.

It automatically strips UTF-8 byte order mark from results.

const readMultipleFiles = require('read-multiple-files');
 
// foo.txt: Hello
// bar.txt: World
 
readMultipleFiles(['foo.txt', 'bar.txt'], 'utf8', (err, contents) => {
  if (err) {
    throw err;
  }
 
  contents; //=> ['Hello', 'World']
});

If it fails to read at least one of the files, it passes an error to the first argument and doesn't pass any values to the second argument.

const readMultipleFiles = require('read-multiple-files');
 
// foo.txt: exists
// bar.txt: doesn't exist
// baz.txt: exists
 
readMultipleFiles(['foo.txt', 'bar.txt', 'baz.txt'], (err, contents) => {
  err.code; //=> 'ENOENT'
  contents; //=> undefined
  arguments.length; //=> 1
});

Related project

License

ISC License © 2017 Shinnosuke Watanabe