How to read from a text file in JavaScript?

The read and write operations in a file can be done by using some commands. But the module which is required to perform these operations is to be imported. The required module is ‘fs’ which is called as File System module in JavaScript.

Write operation on a file

After the File System file is imported then, the writeFile() operation is called. The writeFile() method is used to write into the file in JavaScript. The syntax of this method is as follows −

writeFile(path,inputData,callBackFunction)

The writeFile() function accepts three parameters −

  • Path − The first parameter is the path of the file or the name of the file into which the input data is to be written.

    If there is a file already, then the contents in the file are deleted and the input which is given by the user will get updated or if the file is not present, then the file with that will be created in the given path and the input information is written into it.

  • inputData − The second parameter is the input data which contains the data to be written in the file that is opened.

  • callBackFuntion − The third parameter is the function which is the call back function which takes the error as the parameter and shows the fault if the write operation fails.

Example 1

Following is an example of the write operation in files in JavaScript.

const fs = require('fs') let fInput = "You are reading the content from Tutorials Point" fs.writeFile('tp.txt', fInput, (err) => { if (err) throw err; else{ console.log("The file is updated with the given data") } })

If you open input file you can observe the written data in it as shown below −

How to read from a text file in JavaScript?

Reading from the file

After the File System module is imported, the reading of the file in JavaScript can be done by using the readFile() function.

Syntax

The syntax to read from a file is as follows −

readFile(path, format, callBackFunc)

The readFile() function accepts three parameters including one optional parameter.

  • Path − The first parameter is the path of the test file from which the contents are to read. If the current location or directory is the same directory where the file which is to be opened and read is located then, only the file name has to be given.

  • Format − The second parameter is the optional parameter which is the format of the text file. The format can be ASCII, utf-8 etc.

  • CallBackFunc − The third parameter is the call back function which takes the error as the parameter and displays the fault is any raised due to the error.

Example 2

Following example tries to read the contents of the file populate in the previous example and print it −

const fs = require('fs') fs.readFile('tp.txt', (err, inputD) => { if (err) throw err; console.log(inputD.toString()); })

Output

Following is the output of the above example −

You are reading the content from Tutorials Point

The text which is displayed in the console is the text which is in the given file.

Example 3

Following is a combined example of the above of reading and writing files using the fs module on node.js. Let us create a JS file named main.js having the following code −

Selecting and interacting with files on the user's local device is one of the most commonly used features of the web. It allows users to select files and upload them to a server, for example, uploading photos, or submitting tax documents, etc. But, it also allows sites to read and manipulate them without ever having to transfer the data across the network.

The modern File System Access API

The File System Access API provides an easy way to both read from and write to files and directories on the user's local system. It's currently available in most Chromium-based browsers such as Chrome or Edge. To learn more about it, see the File System Access API article.

Since the File System Access API is not compatible with all browsers yet, check out browser-fs-access, a helper library that uses the new API wherever it is available, but falls back to legacy approaches when it is not.

Working with files, the classic way

This guide shows you how to:

  • Select files

Select files

HTML input element

The easiest way for users to select files is using the <input type="file"> element, which is supported in every major browser. When clicked, it lets a user select a file, or multiple files if the attribute is included, using their operating system's built-in file selection UI. When the user finishes selecting a file or files, the element's change event fires. You can access the list of files from event.target.files, which is a

<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
0 object. Each item in the
<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
0 is a
<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
2 object.

<!-- The `multiple` attribute lets users select multiple files. -->
<input type="file" id="file-selector" multiple>
<script>
const fileSelector = document.getElementById('file-selector');
fileSelector.addEventListener('change', (event) => {
const fileList = event.target.files;
console.log(fileList);
});
</script>

Check if the method is a viable alternative for your use case, since it also gives you a file handle so you can possibly write back to the file, in addition to reading. This method can be .

This example lets a user select multiple files using their operating system's built-in file selection UI and then logs each selected file to the console.

Limit the types of files users can select

In some cases, you may want to limit the types of files users can select. For example, an image editing app should only accept images, not text files. To do that, add an attribute to the input element to specify which file types are accepted.

<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">

Custom drag-and-drop

In some browsers, the <input type="file"> element is also a drop target, allowing users to drag-and-drop files into your app. But, the drop target is small, and can be hard to use. Instead, once you've provided the core functionality using an <input type="file"> element, you can provide a large, custom drag-and-drop surface.

Check if the method is a viable alternative for your use case, since it also gives you a file handle so you can possibly write back to the file, in addition to reading.

Choose your drop zone

Your drop surface depends on the design of your application. You may only want part of the window to be a drop surface, or potentially the entire window.

How to read from a text file in JavaScript?
Squoosh makes the entire window a drop zone.

Squoosh allows the user to drag and drop an image anywhere into the window, and clicking select an image invokes the <input type="file"> element. Whatever you choose as your drop zone, make sure it's clear to the user that they can drag and drop files onto that surface.

Define the drop zone

To enable an element to be a drag-and-drop zone, you'll need to listen for two events,

<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
9 and
const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
event.stopPropagation();
event.preventDefault();
// Style the drag-and-drop as a "copy file" operation.
event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
event.stopPropagation();
event.preventDefault();
const fileList = event.dataTransfer.files;
console.log(fileList);
});
0. The
<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
9 event updates the browser UI to visually indicate that the drag-and-drop action is creating a copy of the file. The
const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
event.stopPropagation();
event.preventDefault();
// Style the drag-and-drop as a "copy file" operation.
event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
event.stopPropagation();
event.preventDefault();
const fileList = event.dataTransfer.files;
console.log(fileList);
});
0 event is fired after the user drops the files onto the surface. Similar to the input element, you can access the list of files from
const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
event.stopPropagation();
event.preventDefault();
// Style the drag-and-drop as a "copy file" operation.
event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
event.stopPropagation();
event.preventDefault();
const fileList = event.dataTransfer.files;
console.log(fileList);
});
3, which is a
<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
0 object. Each item in the
<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
0 is a
<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
2 object.

const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
event.stopPropagation();
event.preventDefault();
// Style the drag-and-drop as a "copy file" operation.
event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
event.stopPropagation();
event.preventDefault();
const fileList = event.dataTransfer.files;
console.log(fileList);
});

const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
event.stopPropagation();
event.preventDefault();
// Style the drag-and-drop as a "copy file" operation.
event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
event.stopPropagation();
event.preventDefault();
const fileList = event.dataTransfer.files;
console.log(fileList);
});
7 and
const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
event.stopPropagation();
event.preventDefault();
// Style the drag-and-drop as a "copy file" operation.
event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
event.stopPropagation();
event.preventDefault();
const fileList = event.dataTransfer.files;
console.log(fileList);
});
8 stop the browser's default behavior and allow your code to run instead. Without them, the browser would otherwise navigate away from your page and open the files the user dropped into the browser window.

Check out Custom drag-and-drop for a live demonstration.

What about directories?

Unfortunately, today there isn't a good way to access a directory.

The

const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
event.stopPropagation();
event.preventDefault();
// Style the drag-and-drop as a "copy file" operation.
event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
event.stopPropagation();
event.preventDefault();
const fileList = event.dataTransfer.files;
console.log(fileList);
});
9 attribute on the <input type="file"> element allows the user to choose a directory or directories. It's except for Firefox for Android.

Check if the method is a viable alternative for your use case, since it also gives you a directory handle so you can possibly write back to the directory, in addition to reading. This method can be .

If drag-and-drop is enabled, a user may try to drag a directory into the drop zone. When the drop event is fired, it will include a

<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
2 object for the directory, but does not provide access any of the files within the directory.

Read file metadata

The

<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
2 object contains metadata about the file. Most browsers provide the file name, the size of the file, and the MIME type, though depending on the platform, different browsers may provide different, or additional information.

function getMetadataForFileList(fileList) {
for (const file of fileList) {
// Not supported in Safari for iOS.
const name = file.name ? file.name : 'NOT SUPPORTED';
// Not supported in Firefox for Android or Opera for Android.
const type = file.type ? file.type : 'NOT SUPPORTED';
// Unknown cross-browser support.
const size = file.size ? file.size : 'NOT SUPPORTED';
console.log({file, name, type, size});
}
}

You can see this in action in the

function getMetadataForFileList(fileList) {
for (const file of fileList) {
// Not supported in Safari for iOS.
const name = file.name ? file.name : 'NOT SUPPORTED';
// Not supported in Firefox for Android or Opera for Android.
const type = file.type ? file.type : 'NOT SUPPORTED';
// Unknown cross-browser support.
const size = file.size ? file.size : 'NOT SUPPORTED';
console.log({file, name, type, size});
}
}
4 demo.

Read a file's content

To read a file, use

function getMetadataForFileList(fileList) {
for (const file of fileList) {
// Not supported in Safari for iOS.
const name = file.name ? file.name : 'NOT SUPPORTED';
// Not supported in Firefox for Android or Opera for Android.
const type = file.type ? file.type : 'NOT SUPPORTED';
// Unknown cross-browser support.
const size = file.size ? file.size : 'NOT SUPPORTED';
console.log({file, name, type, size});
}
}
5, which enables you to read the content of a
<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
2 object into memory. You can instruct
function getMetadataForFileList(fileList) {
for (const file of fileList) {
// Not supported in Safari for iOS.
const name = file.name ? file.name : 'NOT SUPPORTED';
// Not supported in Firefox for Android or Opera for Android.
const type = file.type ? file.type : 'NOT SUPPORTED';
// Unknown cross-browser support.
const size = file.size ? file.size : 'NOT SUPPORTED';
console.log({file, name, type, size});
}
}
5 to read a file as an array buffer, a data URL, or text.

function readImage(file) {
// Check if the file is an image.
if (file.type && !file.type.startsWith('image/')) {
console.log('File is not an image.', file.type, file);
return;
}

const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}

The example above reads a

<input type="file" id="file-selector" accept=".jpg, .jpeg, .png">
2 provided by the user, then converts it to a data URL, and uses that data URL to display the image in an
function getMetadataForFileList(fileList) {
for (const file of fileList) {
// Not supported in Safari for iOS.
const name = file.name ? file.name : 'NOT SUPPORTED';
// Not supported in Firefox for Android or Opera for Android.
const type = file.type ? file.type : 'NOT SUPPORTED';
// Unknown cross-browser support.
const size = file.size ? file.size : 'NOT SUPPORTED';
console.log({file, name, type, size});
}
}
9 element. Check out the
function readImage(file) {
// Check if the file is an image.
if (file.type && !file.type.startsWith('image/')) {
console.log('File is not an image.', file.type, file);
return;
}

const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}
0 demo to see how to verify that the user has selected an image file.

Monitor the progress of a file read

When reading large files, it may be helpful to provide some UX to indicate how far the read has progressed. For that, use the

function readImage(file) {
// Check if the file is an image.
if (file.type && !file.type.startsWith('image/')) {
console.log('File is not an image.', file.type, file);
return;
}

const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}
1 event provided by
function getMetadataForFileList(fileList) {
for (const file of fileList) {
// Not supported in Safari for iOS.
const name = file.name ? file.name : 'NOT SUPPORTED';
// Not supported in Firefox for Android or Opera for Android.
const type = file.type ? file.type : 'NOT SUPPORTED';
// Unknown cross-browser support.
const size = file.size ? file.size : 'NOT SUPPORTED';
console.log({file, name, type, size});
}
}
5. The
function readImage(file) {
// Check if the file is an image.
if (file.type && !file.type.startsWith('image/')) {
console.log('File is not an image.', file.type, file);
return;
}

const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}
1 event provides two properties,
function readImage(file) {
// Check if the file is an image.
if (file.type && !file.type.startsWith('image/')) {
console.log('File is not an image.', file.type, file);
return;
}

const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}
4 (the amount read) and
function readImage(file) {
// Check if the file is an image.
if (file.type && !file.type.startsWith('image/')) {
console.log('File is not an image.', file.type, file);
return;
}

const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}
5 (the amount to read).

How do I read a .TXT file in JavaScript?

After the File System module is imported, the reading of the file in JavaScript can be done by using the readFile() function..
Path − The first parameter is the path of the test file from which the contents are to read. ... .
Format − The second parameter is the optional parameter which is the format of the text file..

How to read data from a file in JavaScript?

To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text. // Check if the file is an image.

How to read a line from a text file in JavaScript?

In JavaScript, a built-in method FileReader() alongside the readline module can be used to read a file line by line. The FileReader() method reads the content of files stored on the local system. Moreover, the readline module performs the reading of the content. Both these methods require the source of the file.

How can I read data from a text file?

To read from a text file Use the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.