Daily Archives: July 17, 2020

JavaScript || FileIO.js – Open, Save, & Read Local & Remote Files Using Vanilla JavaScript

The following is a module that handles opening, reading, and saving files in JavaScript. This allows for file manipulation on the client side.

FileIO.js Source

Contents

1. Open File Dialog
2. Reading Files
3. Saving Files
4. Reading Remote URL Files
5. Saving Remote URL Files
6. FileIO.js Namespace
7. More Examples

 

1. Open File Dialog

Syntax is very straightforward. The following demonstrates opening a file dialog to get files from the user.

FileIO.openDialog‘ returns an array of File objects that contains the selected files after the user hits submit. You can specify the accepted file types, as well as if selecting multiple files is allowed or not.


2. Reading Files

The following example demonstrates how to read a file. This allows to read file contents.

FileIO.read‘ accepts either a File, or a Blob as acceptable data to be read.

By default, ‘FileIO.read‘ will read the file contents as text. To read file contents as an array, set the property ‘readAsTypedArray‘ to true. A Uint8Array is returned when this option is set to true.


3. Saving Files

The following example demonstrates how to create and save a file. This allows to save contents to a file.

FileIO.save‘ accepts either a String, Blob, File, or a Uint8Array as acceptable data to be saved.

If the data to be saved is a base64 string, set the property ‘decodeBase64Data‘ to true in order to decode the string before saving. If the bease64 string is a file, this will allow the actual file to be decoded and saved to the client. Note: This action is only performed if the data to be saved is a string.


4. Reading Remote URL Files

The following example demonstrates how ‘FileIO.read‘ can be used to read downloaded file contents from a remote URL.

The example above uses fetch to retrieve data from the remote URL. Once the data is received, ‘FileIO.read‘ can be used to read its file contents.


5. Saving Remote URL Files

The following example demonstrates how ‘FileIO.save‘ can be used to save downloaded file contents from a remote URL to the client.

The example above uses fetch to retrieve data from the remote URL. Once the data is received, ‘FileIO.save‘ can be used to save its file contents.


6. FileIO.js Namespace

The following is the FileIO.js Namespace. Include this in your project to start using!


7. More Examples

Below are more examples demonstrating the use of ‘FileIO.js‘. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.