Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jahredhope/promise-file-reader
Wraps FileReader in a Promise
https://github.com/jahredhope/promise-file-reader
Last synced: 16 days ago
JSON representation
Wraps FileReader in a Promise
- Host: GitHub
- URL: https://github.com/jahredhope/promise-file-reader
- Owner: jahredhope
- License: isc
- Created: 2016-06-09T06:51:55.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2022-06-26T08:49:02.000Z (over 2 years ago)
- Last Synced: 2024-10-19T02:00:38.044Z (29 days ago)
- Language: JavaScript
- Size: 14.6 KB
- Stars: 31
- Watchers: 3
- Forks: 9
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# promise-file-reader
Wraps [FileReader](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) in a Promise![travis ci](https://travis-ci.org/jahredhope/promise-file-reader.svg?branch=master)
[![npm](https://img.shields.io/npm/v/promise-file-reader.svg)](https://www.npmjs.com/package/promise-file-reader)## Install
```
npm install --save promise-file-reader
```## Usage
### Basic syntax
```javascript
const PromiseFileReader = require('promise-file-reader');PromiseFileReader.readAsDataURL(fileData)
.then(newImage)
.catch(err => console.error(err));
```### Example: file input
```javascript
import {readAsDataURL, readAsText, readAsArrayBuffer} from 'promise-file-reader';function newImage(imageDataUrl) {
...
}
function newTextFile(text) {
...
}
function loadedArrayBuffer(arrayBuffer) {
...
}// e.g.
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));
}
}
```