How to Read Text File in JavaScript
- Using the File API in the Browser
- Reading Files in Node.js
- Using Fetch API for Remote Text Files
- Conclusion
- FAQ

Reading text files in JavaScript can seem daunting at first, but it’s a straightforward process once you understand the tools at your disposal. Whether you’re working on a web application or a Node.js project, knowing how to read text files is essential for tasks like loading configuration files or processing user data.
In this tutorial, we will explore different methods to read text files using JavaScript, both in the browser and in a server-side environment. By the end of this guide, you’ll have a clear understanding of how to effectively read text files in JavaScript and be ready to implement these techniques in your own projects.
Using the File API in the Browser
One of the most common ways to read a text file in a web application is by using the File API. This method allows users to select a file from their local system, which your JavaScript code can then read. Here’s how you can achieve this:
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
console.log(content);
};
reader.readAsText(file);
});
In this example, we first set up an event listener for a file input element. When a user selects a file, the change
event triggers, allowing us to access the selected file. We then create a new instance of FileReader
, which is a built-in JavaScript object designed for reading files. The onload
event of the FileReader
is where we retrieve the file’s content once it’s loaded. Finally, we call readAsText(file)
to read the file as plain text.
Output:
Content of the selected text file
This method is particularly useful for interactive web applications where users upload files. It’s efficient and straightforward, making it easy to retrieve and manipulate file contents dynamically.
Reading Files in Node.js
If you’re working with Node.js, reading text files is equally simple but slightly different due to the server-side environment. Node.js provides the fs
(file system) module, which enables you to interact with the file system. Here’s how to read a text file using Node.js:
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
In this code snippet, we first require the fs
module. We then use the readFile
method to read the contents of example.txt
. The second argument specifies the encoding, which is set to utf8
to ensure we read the file as text. The callback function checks for errors and, if there are none, logs the file’s content to the console.
Output:
Content of example.txt
This method is particularly useful for server-side applications, where you often need to read configuration files or data files. It’s efficient and allows you to handle errors gracefully, ensuring your application can respond appropriately if a file is missing or unreadable.
Using Fetch API for Remote Text Files
Another effective way to read text files, especially when they are hosted on a server, is by using the Fetch API. This method is great for web applications that need to load content dynamically from a server. Here’s an example:
fetch('https://example.com/sample.txt')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
In this example, we use the fetch
function to request a text file from a specified URL. The then
method checks if the response is successful and then reads the response as text. If successful, it logs the content to the console. If there’s an error—either from the network or the response—we catch it and log an appropriate message.
Output:
Content of the remote text file
The Fetch API is a modern approach that works well for asynchronous operations. It’s promise-based, which makes handling multiple requests and responses easier compared to older methods like XMLHttpRequest.
Conclusion
Reading text files in JavaScript is an essential skill for developers, whether you’re working on the client side with the File API and Fetch API or on the server side with Node.js. Each method we explored has its unique use cases and advantages, allowing you to choose the right one based on your project’s requirements. With practice, you’ll find that reading and manipulating text files can greatly enhance your applications’ functionality and user experience.
FAQ
-
How can I read a text file from the local file system in a browser?
You can use the File API to allow users to select a file from their local system, which can then be read using a FileReader object. -
What is the best way to read text files in Node.js?
The best way to read text files in Node.js is by using the built-in fs module, which provides methods like readFile for reading file contents easily. -
Can I read text files from a remote server using JavaScript?
Yes, you can use the Fetch API to read text files hosted on a remote server. This method allows you to load content dynamically. -
What encoding should I use when reading text files?
It’s common to use ‘utf8’ encoding when reading text files to ensure that the content is interpreted correctly. -
Are there any limitations when using the File API in the browser?
Yes, the File API requires user interaction to select files, and it cannot access files directly from the file system without user consent.