- How to Read Text File in Javascript Line By Line
- How to Read File Line by Line in JavaScript
- How to Read File Line by Line in JavaScript?
- Example 1: Using FileReader() Method for Reading a File Line by Line in JavaScript
- Example 2: Using “readline” Module for Reading a File Line by Line in JavaScript
- Conclusion
- About the author
- Syed Minhal Abbas
- How to read a file line by line in Node.js
- You might also like.
How to Read Text File in Javascript Line By Line
In this tutorial, you will learn how to read text file in javascript line by line. As a web developer, in some of the applications, it is very common to provide your web users the ability to select a file and upload it to your server.
In case of image upload, we always have to show the image preview before proceeding with the upload process. Similarly, in case of text file upload, we have to show the contents of the text file in a text box.
To read any file in javascript, we can make use of the FileReader object. This object contains the readAsDataURL() method which will help you in generating a base64 encoded string for an image. This base64 encoded string can be used directly as a source in the img tag.
Please check out online base64 to image converter tool to see it in action. To read text files, we can make use of the readAsText() method.
In the following example, we have an input field of type file and a text box. We will select a text file and display its content line by line in the text box. Please have a look over the code example and the steps given below.
- We have 3 elements in the HTML file ( div , input , and textarea ). The div element is just a wrapper for the rest of the elements.
- The input element is of type file which provides us the ability to select a file.
- We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
- We have also included our javascript file script.js with a script tag at the bottom.
- We have selected the input element and the textarea using document.querySelector() method and stored them in the input and textarea variables respectively.
- We have attached a change event listener to the input element.
- In the event handler function, the files property of the input element returns an array of File objects and we are storing that in the files variable.
- We are making use of the if statement to verify whether the files array is empty or not. If the user has selected a file, then the length property will always return value greater than 0. If it is 0, we just want to stop the execution of the function by using the return statement.
- As you know, arrays have a 0-based index. We are getting the first File object by passing an index of 0 and storing it in the file variable.
- We are creating an instance of the FileReader object and storing it in the reader variable.
- We are assigning a custom function to the onload property of the FileReader object. This function will be executed when the load event gets fired.
- In the load event handler function, we are using the result property to get the contents of the text file.
- We are using split() function and passing regex pattern /\r\n|\n/ as a parameter. This will generate an array of lines and we are storing that in the lines variable.
- We are using the join() method to join all lines by a newline character ( \n ). This will return a string and we are setting that string as the value of the textarea element.
- We are assigning a custom function to the onerror property of the FileReader object. This function will be executed when an error event gets fired.
- In the error event handler function, we are calling the alert() method and passing the name property of the error object as a parameter.
- Finally, we are reading the file by calling the readAsText() method and passing the file variable as a parameter.
let input = document.querySelector('input'); let textarea = document.querySelector('textarea'); input.addEventListener('change', () => < let files = input.files; if(files.length == 0) return; const file = files[0]; let reader = new FileReader(); reader.onload = (e) =>< const file = e.target.result; const lines = file.split(/\r\n|\n/); textarea.value = lines.join('\n'); >; reader.onerror = (e) => alert(e.target.error.name); reader.readAsText(file); >);
How to Read File Line by Line in JavaScript
Reading a file through a browser is an essential task for any website that interacts with its users. The file can be accessed without storing it on the internet. JavaScript provides a built-in method, FileReader() which can be used to read a file. Moreover, various NPM modules can also be used to read a file in JavaScript. This post demonstrates various methods for reading a file line by line via JavaScript. The content of this post is as follows:
How to Read File Line by Line in JavaScript?
JavaScript is famous for providing a variety of methods, and properties to facilitate the user. The built-in FileReader() method can read the file content of each line. For instance, the “readline” module is also utilized to access the file and read it line by line. Moreover, users can read the file through websites or local machines.
Example 1: Using FileReader() Method for Reading a File Line by Line in JavaScript
Here, HTML and JavaScript code is practiced showing the usage of the FileReader() method for reading a file line by line using the functionalities of JavaScript.
Example to Read Local text file < / h1 >
In this code, a file selection field is provided by giving the name “readfile” in the tag. After that, a JavaScript file is integrated by providing the source as “test.js”.
JavaScript Code
let file = document. getElementById ( «readfile» ) ;
file. addEventListener ( «change» , function ( ) {
var reader = new FileReader ( ) ;
reader. onload = function ( progressEvent ) {
console. log ( this . result ) ;
} ;
reader. readAsText ( this . files [ 0 ] ) ;
} ) ;
The description of the code is provided here:
- Firstly, getElementById is employed to extract the file “id” by passing the value “readfile”.
- After that, addEventListener is utilized to trigger the file by passing the “change” value.
- Furthermore, the “FileReader()” method is employed for reading the content of a file.
- Finally, the content of the file is returned through “this.result”.
- In the end, “reader.readAsText()” is utilized for reading the file.
The output shows that the “JavaScript.txt” file is selected as a text file from the browser. After selecting the file, line-by-line text “Welcome to JavaScript” and “Welcome to Linuxhint” are read and displayed in the console window.
Example 2: Using “readline” Module for Reading a File Line by Line in JavaScript
Another method is adapted for reading a file by employing the readline module in JavaScript. In this method, a path is required to access the file name. For instance, the code is provided here.
console. log ( «Example to read line by line text» ) ;
const f = require ( ‘fs’ ) ;
const readline = require ( ‘readline’ ) ;
var user_file = ‘./JavaScript.txt’ ;
var r = readline. createInterface ( {
input : f. createReadStream ( user_file )
} ) ;
r. on ( ‘line’ , function ( text ) {
console. log ( text ) ;
} ) ;
- Firstly, the require(“readline”) is employed to read a data stream from a file.
- After that, the filename “./JavaScript.txt” is assigned to the “user_file” variable.
- A readline.createInterface provides an interface for the readline module to read the content of a file.
- Furthermore, a callback “function” is utilized by passing the value “text”.
- Finally, the “console.log()” method is employed to present the content in the console window.
The output shows that “Welcome to JavaScript” and “Welcome to Linuxhint” are read from the “JavaScript.txt” file.
Conclusion
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. In contrast, you can retrieve the file through the website. Two practical examples are provided to extract the content that is found in the text file. Hence, you have learned a method of reading the content of a file.
About the author
Syed Minhal Abbas
I hold a master’s degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.
How to read a file line by line in Node.js
There are multiple ways to read a file line by line in Node.js. Earlier, we discussed how to read a file line by line in Java.
Let us look at Node.js ways of reading a file line by line.
The simplest way of reading a file line by line in Node.js is by using the native fs module’s fs.readFileSync() method:
const fs = require('fs') try // read contents of the file const data = fs.readFileSync('file.txt', 'UTF-8') // split the contents by new line const lines = data.split(/\r?\n/) // print all lines lines.forEach(line => console.log(line) >) > catch (err) console.error(err) >
- It is blocking, which means that it will stop the program execution until the entire file is loaded into the memory.
- It will have a severe impact on memory consumption if the file is in gigabytes or more.
The first issue could be resolved using the non-blocking version fs.readFile() , but reading the entire file into memory is not something you want to do in a production environment.
However, if you want to read small files only, it works fine.
Readline is another Node.js native module that was developed specifically for this purpose — reading one line at a time from any readable stream. You can even use this module to read input data from the command line. Here is how you can access it in your code (no installation required):
const readline = require('readline')
Since the readline module works with readable streams, we have to first create a stream by using the fs module like below:
const rl = readline.createInterface( input: fs.createReadStream('file.txt'), output: process.stdout, terminal: false >)
Now we can listen for the line event on the rl object that will be triggered whenever a new line is read from the stream:
rl.on('line', line => console.log(line) >)
const fs = require('fs') const readline = require('readline') const rl = readline.createInterface( input: fs.createReadStream('file.txt'), output: process.stdout, terminal: false >) rl.on('line', line => console.log(line) >)
line-reader is an open-source module for reading a file line by line in Node.js. You can add it to your project by running the following command in your terminal:
The line-reader module provides the eachLine() method that reads each line of the given file. It takes a callback function with two arguments: the line content and a boolean value specifying whether the line read was the last line of the file. Here is an example:
const lineReader = require('line-reader') lineReader.eachLine('file.txt', (line, last) => console.log(line) >)
Another benefit of using this module is to stop the reading when some condition turns true. It can be achieved by returning false from the callback function:
const lineReader = require('line-reader') lineReader.eachLine('file.txt', line => console.log(line) // stop if line contains `NEW` if (line.includes('NEW')) // stop reading and close the file return false > >)
linebyline is another open-source library that can read a file line by line in Node.js. Let us add it to your project:
This package simply streams the native readline module internally, reads and buffers new lines emitting a line event for each line:
const readline = require('linebyline') // read all lines rl = readline('file.txt') // listen for `line` event rl.on('line', (line, lineCount, byteCount) => console.log(line) >).on('error', err => console.error(err) >)
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.