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

查看:98
本文介绍了使用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 数组访问命令行参数以获取文件名和 FileSystem模块(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 通常有两个长度,第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!

正如@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天全站免登陆