如何读取Node.js中的文件?

时间:2011-08-29 00:16:46

标签: javascript node.js file filesystems fs

在Node.js中,我想读取一个文件,然后console.log()文件的每一行用\n分隔。我怎么能这样做?

4 个答案:

答案 0 :(得分:7)

试试这个:

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

答案 1 :(得分:1)

尝试阅读fs module documentation

答案 2 :(得分:1)

请参阅node.js中的File System API,关于SO的问题也很少,有one of them

答案 3 :(得分:0)

有许多方法可以在Node中读取文件。您可以在the Node documentation about the File System module, fs中了解所有这些内容。

在您的情况下,我们假设您要阅读一个看起来像这样的简单文本文件countries.txt;

Uruguay
Chile
Argentina
New Zealand

首先,您必须{JavaScript}文件顶部的require()模块fs,就像这样;

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来解释在阅读文件时发生的任何可能的错误。您可以将所有代码放在一个名为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');
  });
});

然后,您可以在终端中运行该脚本。导航到包含countries.txtread.js的目录,然后键入node read.js并按Enter键。您应该会在屏幕上看到结果。恭喜!您已经使用Node读取了一个文件!