How to read a file in Node.js?

In Node.js, I want to read a file, and then console.log()every line of the file that is split \n. How can i do this?

+5
source share
4 answers

Try the following:

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);
  });
});
+7
source

Try to read the documentation fs.

+1
source

File System API node.js, SO,

+1

Node. Node , fs.

, countries.txt, :

Uruguay
Chile
Argentina
New Zealand

require() fs JavaScript, :

var fs = require('fs');

, , fs.readFile(), :

fs.readFile('countries.txt','utf8', function (err, data) {});

, {}, readFile. , err, data. data , , ,

fs.readFile('countries.txt','utf8', function (err, data) {
  console.log(data);
});

, ;

Uruguay
Chile
Argentina
New Zealand

, . (\n), , readFile . , ;

fs.readFile('calendar.txt','utf8', function (err, data) {
  // Split each line of the file into an array
  var lines=data.split('\n');

  // Log each line separately, including a newline
  lines.forEach(function(line){
    console.log(line, '\n');
  });
});

;

Uruguay

Chile

Argentina

New Zealand

, , if (err) throw err , data. script, read.js :

var fs = require('fs');
fs.readFile('calendar.txt','utf8', function (err, data) {
  if (err) throw err;
  // Split each line of the file into an array
  var lines=data.split('\n');

  // Log each line separately, including a newline
  lines.forEach(function(line){
    console.log(line, '\n');
  });
});

script . , countries.txt, read.js, node read.js enter. , . ! Node!

0

All Articles