使用 Node.js 读取文本文件? [英] Read a text file using Node.js?

查看:36
本文介绍了使用 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?

推荐答案

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

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

为您稍微分解一下 process.argv 通常长度为 2,第 0 个项目是节点"解释器,第一个项目是节点当前正在运行的脚本,后面的项目在命令行上传递的.从 argv 中提取文件名后,您就可以使用文件系统函数来读取文件并对其内容执行任何您想要的操作.示例用法如下所示:

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. 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. Sample usage would look like this:

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

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

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. 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.

处理大文件(或任何文件,实际上)的节点"方式是使用 fs.read() 并处理每个可用的块,因为它可以从操作系统中获得.但是,这样读取文件需要您自己(可能)对文件进行增量解析/处理,并且可能不可避免地需要一定量的缓冲.

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. 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.

这篇关于使用 Node.js 读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆