How do you call a text file in javascript?

  1. HowTo
  2. JavaScript Howtos
  3. Read Text File in JavaScript

Created: August-10, 2021

  1. Use the blob.text() Function to Read Text Files in JavaScript
  2. Use the FileReader Interface to Read Text Files in JavaScript

JavaScript allows web pages to read and display elements dynamically. In this tutorial, we will learn how to read a text file in JavaScript.

Use the blob.text() Function to Read Text Files in JavaScript

The Blob interface’s blob.text() method delivers a promise that resolves to a string containing the blob’s contents, interpreted as UTF-8. We can use it to read local files.

The <input> tag can be used to select the required file. After selecting the file, we will read its contents using the blob.text() function. We display the output on the webpage.

See the following code.

<!DOCTYPE html>
<html>
  <head>
    <title>Read Text File Tutorial</title>
  </head>
  <body>
    <input type="file" onchange="loadFile(this.files[0])">
    <br>
    <pre id="output"></pre>
    <script>
      async function loadFile(file) {
        let text = await file.text();
        document.getElementById('output').textContent = text;
      }
    </script>
  </body>
</html>

How do you call 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 do you call 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 −

var fs = require("fs"); console.log("Going to write into existing file"); fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) { console.log("Data written successfully!"); console.log("Let's read newly written data"); fs.readFile('input.txt', function (err, data) { console.log("Asynchronous read: " + data.toString()); }); });

How do you call a text file in javascript?

Updated on 02-Sep-2022 12:17:02

  • Related Questions & Answers
  • Read/Write structure to a file using C
  • Read and Write to an excel file using Python openpyxl module
  • How to open a file in read and write mode with Python?
  • How to set read and write position in a file in Python?
  • Write a C program to read a data from file and display
  • How to open a binary file in read and write mode with Python?
  • How to read data from *.CSV file using JavaScript?
  • How can we read & write a file using Gson streaming API in Java?
  • How to read data from a file using FileInputStream?
  • How to read/write data from/to .properties file in Java?
  • Read/Write Class Objects from/to File in C++
  • How to read a cookie using JavaScript?
  • How to create a file, write data into it and read data from it on iOS?
  • Write a Python program to read an Excel data from file and read all rows of first and last columns
  • How to use seek() method to reset a file read/write position in Python?

How do I open a text file in JavaScript?

Here is simple example for reading a text file using JavaScript..
function read().
var txtFile = new XMLHttpRequest();.
txtFile.onreadystatechange = function().
if (txtFile.readyState === 4).
// Makes sure the document is ready to parse..

How do I import a text file into JavaScript?

Import fs-module in the program and use functions to read text from the files in the system..
Input. ... .
Script.js: ... .
Instead of converting buffer into text using tostring function, directly get the data into text format also..

Can JavaScript write to a text file?

There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs. js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system.

How do I read a text file in HTML?

HTML 5 provides a standard way to interact with local files with the help of File API. The File API allows interaction with single, multiple as well as BLOB files. The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling.