In Node.js, I want to read a file, and then console.log()
each line of the file separated by \n
. How can I do that?
To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text. // Check if the file is an image.
Method 1: Using the Readline Module: Readline is a native module of Node. js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. const readline = require('readline');
Try this:
var fs=require('fs');
fs.readFile('/path/to/file','utf8', function (err, data) {
if (err) throw err;
var arr=data.split('\n');
arr.forEach(function(v){
console.log(v);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With