6

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

4

4 回答 4

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);
  });
});
于 2011-08-29T00:24:48.637 回答
1

尝试阅读fs模块文档

于 2011-08-29T00:19:38.393 回答
1

请参考 node.js 中的File System API,SO 上类似的问题也很少,有一个

于 2011-08-29T00:19:48.573 回答
0

在 Node.js 中读取文件有很多方法。您可以在有关文件系统模块的 Node 文档中了解所有这些内容,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.txt和的目录,read.js然后键入node read.js并按 Enter。您应该会在屏幕上看到已注销的结果。恭喜!你已经用 Node 读取了一个文件!

于 2017-05-22T17:58:08.220 回答