使用 Node.js 读取文本文件?

我需要在终端传入一个文本文件,然后从中读取数据,我该怎么做?

node server.js file.txt

如何传递来自终端的路径,如何读取另一端的路径?

308814 次浏览

您需要使用 process.argv数组来访问命令行参数以获取文件名,并使用 FileSystem 模块(fs)来读取文件。例如:

// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
// Read the file and print its contents.
var fs = require('fs')
, filename = process.argv[2];
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});

为了让你更好的理解,process.argv的长度通常是2,第0个项目是“ node”解释器,第1个项目是节点当前运行的脚本,之后的项目在命令行上传递。从 argv 中提取文件名之后,就可以使用文件系统函数读取文件并对其内容进行任何处理。样本使用情况如下:

$ node ./cat.js file.txt
OK: file.txt
This is file.txt!

[ Edit ] 正如@wtfcoder 提到的,使用“ fs.readFile()”方法可能不是最好的主意,因为它将缓冲文件的整个内容,然后将其提供给回调函数。这种缓冲可能会使用大量内存,但更重要的是,它没有利用 node.js 的一个核心特性——异步的事件 I/O。

处理大型文件(或任何文件)的“节点”方法是使用 fs.read()并处理操作系统中可用的每个可用块。然而,以这种方式读取文件需要您自己(可能)对文件进行增量解析/处理,并且可能不可避免地要进行一些缓冲。

恕我直言,应该避免使用 fs.readFile(),因为它会加载内存中的所有文件,并且在读取所有文件之前不会调用回调函数。

读取文本文件最简单的方法是逐行读取。我推荐使用 BufferedReader:

new BufferedReader ("file", { encoding: "utf8" })
.on ("error", function (error){
console.log ("error: " + error);
})
.on ("line", function (line){
console.log ("line: " + line);
})
.on ("end", function (){
console.log ("EOF");
})
.read ();

用于复杂的数据结构,如。属性或 json 文件,您需要使用一个解析器(在内部,它还应该使用一个缓冲读取器)。

可以使用 readstream 和管道逐行读取文件,而无需将所有文件一次性读入内存。

var fs = require('fs'),
es = require('event-stream'),
os = require('os');


var s = fs.createReadStream(path)
.pipe(es.split())
.pipe(es.mapSync(function(line) {
//pause the readstream
s.pause();
console.log("line:", line);
s.resume();
})
.on('error', function(err) {
console.log('Error:', err);
})
.on('end', function() {
console.log('Finish reading.');
})
);

我张贴了一个完整的例子,我终于得到了工作。在这里,我从一个脚本 rooms/rooms.js读取文件 rooms/rooms.txt

var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
console.log(data);
});

用节点命名 fs。

var fs = require('fs');


try {
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());
} catch(e) {
console.log('Error:', e.stack);
}

异步的生活方式:

#! /usr/bin/node


const fs = require('fs');


function readall (stream)
{
return new Promise ((resolve, reject) => {
const chunks = [];
stream.on ('error', (error) => reject (error));
stream.on ('data',  (chunk) => chunk && chunks.push (chunk));
stream.on ('end',   ()      => resolve (Buffer.concat (chunks)));
});
}


function readfile (filename)
{
return readall (fs.createReadStream (filename));
}


(async () => {
let content = await readfile ('/etc/ssh/moduli').catch ((e) => {})
if (content)
console.log ("size:", content.length,
"head:", content.slice (0, 46).toString ());
})();