- How to read a file line by line in Node.js
- You might also like.
- 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 text file in JavaScript (line by line)
- What is FileReader() ?
- Read Local Text File Using JavaScript
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.
You might also like.
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 text file in JavaScript (line by line)
In this article, we will learn how to read text files line-by-line using JavaScript.
We can read and view the content of the text file using FileReader() object in our browser or terminal using JavaScript.
What is FileReader() ?
The FileReader() is an object provided by JavaScript that let a web-application read content of files stored on a user’s computer. It uses File or Blob object to specify or read the content of the file.
FileReader can read text files that the user specifically selected.
Let us see with an example.
Read Local Text File Using JavaScript
Here, we will upload a simple text file (.txt) using an HTML input field and display the content of it on our terminal / console.
h1> Read Local text file using JavaScript h1> input type="file" name="myfile" id="myfile" /> p>check console for result p> script src="main.js"> script>
JavaScript code:
let file = document.getElementById("myfile"); file.addEventListener("change", function ( ) < var reader = new FileReader(); reader.onload = function (progressEvent) < console.log(this.result); >; reader.readAsText(this.files[0]); >);
Code Explanation
Here, we have an input field that helps us to select a text file from our computer.
In the Script file, we have selected the file using getElementById() .
We have added an event listener to the file, which listens to an change event. It gets triggered when a file is selected in the input field.
Once the change event is triggered the function will read the file using FileReader() and then console.log the content inside it to the terminal of your browser.
reader.onload : It runs once the reading operation is completed.
readAsText() : This method reads the file content of the selected Blob or File
this.result : It returns the file content on the terminal.
Related Topics: