How to read and write file lines with Node.js and JavaScript?

Sometimes, we want to read and write file lines with Node.js and JavaScript.

In this article, we’ll look at how to read and write file lines with Node.js and JavaScript.

How to read and write file lines with Node.js and JavaScript?

To read and write file lines with Node.js and JavaScript, we can call the readFileSync method to read the file into a string.

Then we call JavaScript string’s split method to split the string into an array.

And we loop through the array to write each line to the file with appendFileSync.

For instance, we write:

const fs = require("fs");

for (const line of fs.readFileSync('./input.txt').toString().split('n')) {
  console.log(line);
  fs.appendFileSync("./output.txt", line.toString() + "n");
};

We call readFileSync with the path to the file.

Then we call toString to convert the file into a string.

Next, we call split to split the string into an array.

Then we use the for-of loop to loop through each line.

And finally, we call appendFileSync to write the line into the output.txt file.

Conclusion

To read and write file lines with Node.js and JavaScript, we can call the readFileSync method to read the file into a string.

Then we call JavaScript string’s split method to split the string into an array.

And we loop through the array to write each line to the file with appendFileSync.