简体   繁体   English

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

[英]Read a text file using Node.js?

I need to pass in a text file in the terminal and then read the data from it, how can I do this?我需要在终端中传入一个文本文件,然后从中读取数据,我该怎么做?

node server.js file.txt

How do I pass in the path from the terminal, how do I read that on the other side?如何从终端传入路径,如何在另一侧阅读?

You'll want to use the process.argv array to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file.您需要使用process.argv数组来访问命令行参数以获取文件名和FileSystem 模块 (fs)以读取文件。 For example:例如:

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

To break that down a little for you process.argv will usually have length two, the zeroth item being the "node" interpreter and the first being the script that node is currently running, items after that were passed on the command line.为您分解一下process.argv通常长度为 2,第 0 个项目是“节点”解释器,第一个项目是节点当前正在运行的脚本,之后的项目在命令行上传递。 Once you've pulled a filename from argv then you can use the filesystem functions to read the file and do whatever you want with its contents.从 argv 中提取文件名后,您就可以使用文件系统函数来读取文件并对其内容执行任何您想要的操作。 Sample usage would look like this:示例用法如下所示:

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

[Edit] As @wtfcoder mentions, using the " fs.readFile() " method might not be the best idea because it will buffer the entire contents of the file before yielding it to the callback function. [编辑]正如@wtfcoder 所提到的,使用“ fs.readFile() ”方法可能不是最好的主意,因为它会在将文件交给回调函数之前缓冲文件的全部内容。 This buffering could potentially use lots of memory but, more importantly, it does not take advantage of one of the core features of node.js - asynchronous, evented I/O.这种缓冲可能会使用大量内存,但更重要的是,它没有利用 node.js 的核心特性之一——异步、事件 I/O。

The "node" way to process a large file (or any file, really) would be to use fs.read() and process each available chunk as it is available from the operating system.处理大文件(或任何文件,实际上)的“节点”方法是使用fs.read()并处理每个可用的块,因为它可以从操作系统中获得。 However, reading the file as such requires you to do your own (possibly) incremental parsing/processing of the file and some amount of buffering might be inevitable.但是,这样读取文件需要您自己(可能)对文件进行增量解析/处理,并且某些缓冲量可能是不可避免的。

Usign fs with node.使用节点对 fs 进行签名。

var fs = require('fs');

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

IMHO, fs.readFile() should be avoided because it loads ALL the file in memory and it won't call the callback until all the file has been read.恕我直言,应该避免fs.readFile()因为它将所有文件加载到内存中,并且在读取所有文件之前它不会调用回调。

The easiest way to read a text file is to read it line by line.阅读文本文件最简单的方法是逐行阅读。 I recommend a BufferedReader :我推荐一个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 ();

For complex data structures like .properties or json files you need to use a parser (internally it should also use a buffered reader).对于像 .properties 或 json 文件这样的复杂数据结构,您需要使用解析器(在内部它也应该使用缓冲读取器)。

You can use readstream and pipe to read the file line by line without read all the file into memory one time.您可以使用 readstream 和 pipe 逐行读取文件,而无需一次将所有文件读入内存。

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

I am posting a complete example which I finally got working.我发布了一个完整的例子,我终于开始工作了。 Here I am reading in a file rooms/rooms.txt from a script rooms/rooms.js在这里,我读文件rooms/rooms.txt从脚本rooms/rooms.js

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

The async way of life:异步生活方式:

#! /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 ());
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM