如何在 Node.js 中读取文件?
在 Node.js 中,我想读取一个文件,然后使用 console.log()
文件的每一行以 \n
分隔。我怎样才能做到这一点?
In Node.js, I want to read a file, and then console.log()
each line of the file separated by \n
. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
Try this:
尝试阅读
fs
模块文档。Try reading the
fs
module documentation.请参考node.js中的文件系统 API,也很少关于SO的类似问题,有其中一个
Please refer to the File System API's in node.js, there is also few similar questions on SO, there is one of them
Node.js 中读取文件的方法有很多种。您可以在 有关该文件的 Node 文档中了解所有内容系统模块,
fs
。对于您的情况,假设您想要读取一个简单的文本文件
countries.txt
,如下所示;首先,您必须在 JavaScript 文件顶部
require()
fs
模块,如下所示;然后要使用它读取文件,您可以使用
fs.readFile()
方法,像这样;现在,在
{}
内,您可以与readFile
方法的结果进行交互。如果出现错误,结果将存储在err
变量中,否则,结果将存储在data
变量中。您可以在此处记录data
变量以查看您正在使用的内容;如果你做得正确,你应该在终端中获得文本文件的确切内容;
我想这就是你想要的。您的输入由换行符 (
\n
) 分隔,并且输出也将如此,因为readFile
不会更改文件的内容。如果需要,您可以在记录结果之前更改文件;这将在每行之间添加一个额外的换行符;
您还应该通过在首次访问
data
之前的行上添加if (err) throw err
来解决读取文件时可能发生的任何错误。您可以将所有这些代码放在一个名为read.js
的脚本中,如下所示;然后您可以在终端中运行该脚本。导航到包含
countries.txt
和read.js
的目录,然后输入node read.js
并按 Enter 键。您应该会在屏幕上看到注销的结果。恭喜!您已经使用 Node 读取了一个文件!There are many ways to read a file in Node. You can learn about all of them in the Node documentation about the File System module,
fs
.In your case, let's assume that you want to read a simple text file,
countries.txt
that looks like this;First you have to
require()
thefs
module at the top of your JavaScript file, like this;Then to read your file with it, you can use the
fs.readFile()
method, like this;Now, inside the
{}
, you can interact with the results of thereadFile
method. If there was an error, the results will be stored in theerr
variable, otherwise, the results will be stored in thedata
variable. You can log thedata
variable here to see what you're working with;If you did this right, you should get the exact contents of the text file in your terminal;
I think that's what you want. Your input was separated by newlines (
\n
), and the output will be as well sincereadFile
doesn't change the contents of the file. If you want, you can make changes to the file before logging the results;That will add an extra newline between each line;
You should also account for any possible errors that happen while reading the file by adding
if (err) throw err
on the line right before you first accessdata
. You can put all of that code together in a script calledread.js
like this;You can then run that script in your Terminal. Navigate to the directory that contains both
countries.txt
andread.js
, and then typenode read.js
and hit enter. You should see the results logged out on the screen. Congratulations! You've read a file with Node!