node read file line
- Import the file system module:
const fs = require('fs');
This line of code imports the built-in file system module in Node.js. The fs
module provides methods for interacting with the file system.
- Read the file:
const fileContent = fs.readFileSync('file.txt', 'utf-8');
Here, we use the readFileSync
method from the fs
module to read the contents of a file called file.txt
. The second argument, 'utf-8'
, specifies the encoding of the file.
- Split the content into lines:
const lines = fileContent.split('\n');
The split
method is used to split the content of the file into an array of lines. We use the newline character ('\n'
) as the delimiter to split the content into lines.
- Iterate over the lines:
lines.forEach((line) => {
console.log(line);
});
In this step, we use the forEach
method to iterate over each line in the lines
array. For each line, we log it to the console using console.log
.
That's it! These steps demonstrate how to read a file line by line in Node.js using the fs
module.