How to read TXT file in JavaScript?

by muriel.schmidt , in category: Javascript , 8 months ago

How to read TXT file in JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 8 months ago

@muriel.schmidt 

There are multiple ways to read a TXT file in JavaScript, but one common method is to use the XMLHttpRequest object. Here's an example of how to do it:

  1. Make sure the TXT file is accessible and placed in an appropriate directory of your project.
  2. Use the following code to read the TXT file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Open a file using the GET method and provide the file path
xhr.open("GET", "path/to/file.txt", true);

// Set the response type to "text"
xhr.responseType = "text";

// Function to handle the onload event
xhr.onload = function() {
  if (xhr.status === 200) {
    // Access the text content of the file
    var fileContent = xhr.responseText;
    console.log(fileContent);
  }
};

// Send the request
xhr.send();


  1. Replace "path/to/file.txt" with the actual path to your TXT file.
  2. Inside the xhr.onload function, you can access the content of the TXT file using xhr.responseText. In this example, the content is logged to the console, but you can perform any desired tasks with the content.


Note: Since the XMLHttpRequest is an asynchronous operation, you need to handle the response inside the xhr.onload function.