https://github.com/loopmode/read-local-files
A function for reading local files from the browser
https://github.com/loopmode/read-local-files
Last synced: about 1 year ago
JSON representation
A function for reading local files from the browser
- Host: GitHub
- URL: https://github.com/loopmode/read-local-files
- Owner: loopmode
- Created: 2018-03-30T11:30:50.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2019-12-18T18:34:56.000Z (over 6 years ago)
- Last Synced: 2025-02-11T00:48:14.423Z (about 1 year ago)
- Language: TypeScript
- Size: 27.3 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
# read-local-files
Launches the native "open file" dialog and allows the user to choose one or more file to read contents from.
The function returns a promise that is resolved when the user picks files and rejected when the user cancels.
Cancel detection happens using `focus` and `mousemove` event listeners on the window object.
Once the user confirms the native file select dialog, the promise is resolved with an array of `FileReader` objects. Each has a `result` property that holds the content of the loaded file.
If the user cancels the dialog, the promise is rejected with an `ERR_ABORTED` error.
## Installation
```javascript
yarn add @loopmode/read-local-files
```
## Usage
In the example we expect to user to open json files.
Using `async/await`
```javascript
import readLocalFiles from '@loopmode/read-local-files';
async function handleLoadClick() {
try {
const fileInputs = await readLocalFiles();
const data = fileInputs.map(input => JSON.parse(input.result))
console.log({data})
} catch (error) {
console.warn(error);
}
}
```
## Options
You shouldn't really need these..
`encoding` - Used for `FileReader.readAsText`. Defaults to `UTF-8`.
See https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsText#Parameters
`rejectTimeout` - Amount of milliseconds to wait before rejecting the promise. Defaults to 500.
The promise is rejected on `mousemove` or `focus`, but this may happen just as well when the user actually did choose a file, and the dialog gets closed by the browser. In order to not immediatly reject the promise, we wait for `rejectTimeout` millis. If the files have been handled by now, we do not reject the promise.