promise-file-reader

Wraps FileReader in a Promise


Keywords
Promise, FileReader, FileAPI, File API, File
License
ISC
Install
npm install promise-file-reader@1.0.2

Documentation

promise-file-reader

Wraps FileReader in a Promise

travis ci npm

Install

npm install --save promise-file-reader

Usage

Basic syntax

const PromiseFileReader = require('promise-file-reader');

PromiseFileReader.readAsDataURL(fileData)
  .then(newImage)
  .catch(err => console.error(err));

Example: file input

import {readAsDataURL, readAsText, readAsArrayBuffer} from 'promise-file-reader';

function newImage(imageDataUrl) {
  ...
}
function newTextFile(text) {
  ...
}
function loadedArrayBuffer(arrayBuffer) {
  ...
}

// e.g. <input id="file-input" type="file" />
const fileInput = document.getElementById('file-input');
fileInput.addEventListener("change", handleFiles, false);
function handleFiles(event) {
  const fileMetaData =  event.target.files[0];

  if(fileMetaData) {
    if (/^image/.test(fileMetaData.type)) {
      readAsDataURL(fileMetaData)
      .then(newImage)
      .catch(err => console.error(err));
    } else {
      readAsText(fileMetaData)
      .then(newTextFile)
      .catch(err => console.error(err));
    }
    // or
    readAsArrayBuffer(fileMetaData)
      .then(loadedArrayBuffer)
      .catch(err => console.error(err));
  }
}