- Get file contents with javascript
- Using readFileSync() — Synchronous function
- Using readFile() — Asynchronous function
- How To Read and Process Files with the JavaScript FileReader API
- Prerequisites
- Uploading a File
- Using File Blob Properties
- Applying FileReader Lifecycle and Methods
- Using FileReaderSync
- Conclusion
Get file contents with javascript
December 13, 2020 — 4 min read
To get the contents of a file as a string, we can use the readFileSync() or readFile() functions from the native filesystem ( fs ) module in Node.js.
/* Get all the contents from a file */ const content = readFileSync("myFile.txt");
- The readFileSync() function is used to synchronously read the contents from a file which further blocks the execution of code in Nodejs.
- The readFile() function is used to asynchronously read the contents from a file in Node.js.
For example, Let’s say we have a file called myFile.txt and we want to read all the contents from it as a string.
First thing we have to do is require() or import the filesystem module like this,
// get filesystem module const fs = require("fs");
Using readFileSync() — Synchronous function
Now we can use the readFileSync() function from the fs module and pass the path to the file.
// get filesystem module const fs = require("fs"); // using the readFileSync() function // and passing the path to the file const buffer = fs.readFileSync("myFile.txt"); console.log(buffer); /* */
Since it is a Buffer we can use the toString() method on the Buffer object to get the contents as String .
// get filesystem module const fs = require("fs"); // using the readFileSync() function // and passing the path to the file const buffer = fs.readFileSync("myFile.txt"); // use the toString() method to convert // Buffer into String const fileContent = buffer.toString(); console.log(fileContent); /* Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut consequat. . */
- Since the myFile.txt file is in the same folder as the running script, we don’t need to resolve the path. But sometimes you need to resolve the path because the directory and the script may not be in the same directory, for that you can use the path module in Node.js to achieve that.
Using readFile() — Asynchronous function
Now let’s use the readFile() function from the fs module.
Here the function needs 2 arguments,
- The First argument is the path to the file.
- The second one is an error first callback function which will get executed when all the contents inside the file are read. The callback function receives an error object as the first parameter if any, and a Buffer object as the second parameter.
// get filesystem module const fs = require("fs"); // using the readFile() function // and passing the path to the file // as the first argument // callback function as the second argument // which will execute after contents of file read fs.readFile("myFile.txt", (err, buff) => < // if any error if (err) < console.error(err); return; > // otherwise log contents console.log(buff.toString()); /* Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut consequat. . */ >);
- Since it is a buffer, we can use the toString() method on the Buffer object to get the contents as String .
And this is how we can read the contents from the file as String .
How To Read and Process Files with the JavaScript FileReader API
In this article, you will explore the File , FileReader , and FileReaderSync APIs.
Prerequisites
If you would like to follow along with this article, you will need:
- An understanding of JavaScript methods, EventListener , and Promises will be helpful.
- A code editor.
- A modern web browser that supports File , FileReader , and FileReaderSync .
Uploading a File
First, to get a file from a user, we need to use an element:
This code will let users upload files from their machines.
Here’s an example of uploading a file using an HTML :
form enctype="multipart/form-data" action="/upload" method="post"> input id="input" type="file" /> form>
For greater control in handling uploads, you can use JavaScript instead of an HTML to submit the files:
let file = document.getElementById('input').files[0]; let formData = new FormData(); formData.append('file', file); fetch('/upload/image', method: "POST", body: formData>);
Using File Blob Properties
In modern browsers, Files have Blob properties and functions. These functions allows us to read the file.
- .text() transforms the file into a stream and then into a string.
- .stream() returns a ReadableStream .
- .arrayBuffer() returns an ArrayBuffer that contains the blob’s data in binary form.
- .slice() allows you to get slices of the file.
Create a new myFile.txt file with some text:
Then, create a new file-blob-example.html file:
!DOCTYPE html> html> body> input type="file" id="input" /> script> const streamToText = async (blob) => const readableStream = await blob.getReader(); const chunk = await readableStream.read(); return new TextDecoder('utf-8').decode(chunk.value); >; const bufferToText = (buffer) => const bufferByteLength = buffer.byteLength; const bufferUint8Array = new Uint8Array(buffer, 0, bufferByteLength); return new TextDecoder().decode(bufferUint8Array); >; document.getElementById('input').addEventListener('change', function(e) let file = document.getElementById('input').files[0]; (async () => const fileContent = await file.text(); console.log('.text()', fileContent); const fileContentStream = await file.stream(); console.log('.stream()', await streamToText(fileContentStream)); const buffer = await file.arrayBuffer(); console.log('.buffer()', bufferToText(buffer)); const fileSliceBlob = file.slice(0, file.length); const fileSliceBlobStream = await fileSliceBlob.stream(); console.log('.slice() and .stream()', await streamToText(fileSliceBlobStream)); >)(); >); /script> /body> /html>
Open file-blob-example.html in your web browser and add the myFile.txt file to the input . In your web developer console, you will see the file contents read out using .text() , .stream() , .buffer() , and .slice() .
Applying FileReader Lifecycle and Methods
There are 6 main events attached to FileReader:
- loadstart : Fires when we start loading a file.
- progress : Fires when the blob is read in memory.
- abort : Fires when we call .abort .
- error : Fires when an error occurs.
- load : Fires when the read is successful.
- loadend : Fires when the file is loaded and if error or abort didn’t get called or if load starts a new read.
To start loading our file we have four methods:
- readAsArrayBuffer(file) : Reads the file or blob as an array buffer. One use case is to send large files to a service worker.
- readAsBinaryString(file) : Reads the file as a binary string
- readAsText(file, format) : Reads the file as USVString (almost like a string), and you can specify an optional format.
- readAsDataURL(file) : This will return a URL where you can access the file’s content, it is Base64 encoded and ready to send to your server
Create a new filereader-example.html file that uses readAsDataURL() :
DOCTYPE html> html> head> style> body background: #000; color: white; > #progress-bar margin-top: 1em; width: 100vw; height: 1em; background: red; transition: 0.3s; > style> head> body> input type="file" id="input" /> progress value="0" max="100" id="progress-bar">progress> div id="status">div> script> const changeStatus = (status) => document.getElementById('status').innerHTML = status; > const setProgress = (e) => const fr = e.target; const loadingPercentage = 100 * e.loaded / e.total; document.getElementById('progress-bar').value = loadingPercentage; > const loaded = (e) => const fr = e.target; var result = fr.result; changeStatus('Finished Loading!'); console.log('Result:', result); > const errorHandler = (e) => changeStatus('Error: ' + e.target.error.name); > const processFile = (file) => const fr = new FileReader(); fr.readAsDataURL(file); fr.addEventListener('loadstart', changeStatus('Start Loading')); fr.addEventListener('load', changeStatus('Loaded')); fr.addEventListener('loadend', loaded); fr.addEventListener('progress', setProgress); fr.addEventListener('error', errorHandler); fr.addEventListener('abort', changeStatus('Interrupted')); > document.getElementById('input').addEventListener('change', (e) => const file = document.getElementById('input').files[0]; if (file) processFile(file); > >); script> body> html>
Open filereader-example.html in your web browser and add the myFile.txt file to the input . A progress bar will appear on the screen as the file is processed. If it loads successfully, it will indicate ‘Start Loading’ , ‘Loaded’ , and ‘Finished Loading’ .
Using FileReaderSync
FileReader is an asynchronous API because we do not want to block the main thread while reading files. For example, we don’t want our user interface to stop working when the browser is trying to read a very large file. However, there is a synchronous version of FileReader called FileReaderSync . We can only use FileReaderSync in Web Workers. Web workers have their own thread so they won’t block the main thread. FileReaderSync uses the same methods as FileReader :
- FileReaderSync.readAsArrayBuffer()
- FileReaderSync.readAsBinaryString()
- FileReaderSync.readAsText()
- FileReaderSync.readAsDataURL()
There are no event handlers because it’s synchronous.
Conclusion
In this article, you explored the File , FileReader , and FileReaderSync APIs.
Take the time to check the browser support for these features to ensure that they are applicable to the users of your projects.
Continue your learning with additional Web APIs.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.