read-multiple-files

Read multiple files asynchronously


Keywords
fs, read, reader, multiple, parallel, parallelly, file, files, observable, contents, buffer, async, asynchronous, asynchronously, filesystem, javascript, nodejs
License
ISC
Install
npm install read-multiple-files@3.0.0

Documentation

read-multiple-files

npm version Build Status Coverage Status

Read multiple files Observable way

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

readMultipleFiles(new Set([
  'one.txt',    // 'a'
  'another.txt' // 'b'
])).subscribe({
  next(result) {
    if (result.path === 'one.txt') {
      result.contents; // Buffer.from('a')
    } else if (result.path === 'another.txt') {
      result.contents; // Buffer.from('b')
    }
  },
  complete() {
    console.log('Successfully read all files.');
  }
});

Installation

Use npm.

npm install read-multiple-files

API

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

readMultipleFiles(paths [, options])

paths: <Array|Set<string|Buffer|URL|integer>> (file paths)
options: Object (fs.readFile options) or string (encoding)
Return: Observable (Kevin Smith's implementation)

When the Observable is subscribed, it starts to read files in parallel, successively send each result to its Observer as an Object: {path: <string|Buffer|URL|integer>, contents: <string:Buffer>}

readMultipleFiles([
  'foo.txt', // 'Hello'
  'bar.txt'  // 'World'
], 'utf8').subscribe({
  next({path, contents}) {
    if (path === 'one.txt') {
      contents; // 'Hello'
    } else if (path === 'another.txt') {
      contents; // 'World'
    }
  }
});

The Observer receives an error when it fails to read at least one of the files.

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

readMultipleFiles([
  'foo.txt', // exists
  'bar.txt'  // doesn't exist
]).subscribe({
  error(err) {
    err.code; //=> ENOENT
  },
  complete() {
    // `complete` callback will never be called.
  }
});

Related project

License

ISC License © 2017 - 2018 Shinnosuke Watanabe