Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a file in Node.js?

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?

like image 928
user847495 Avatar asked Aug 29 '11 00:08

user847495


People also ask

How do you read a file in JavaScript?

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.

How do I read a file line by line in node JS?

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');


1 Answers

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);
  });
});
like image 90
stewe Avatar answered Nov 10 '22 07:11

stewe