Javascript程序如何读取文本文件?

2021年3月23日15:16:43 发表评论 961 次浏览

先决条件:如何使用JavaScript导入库。从这里阅读:JavaScript |导入和导出模块.

给定一个文本文件, 编写一个JavaScript程序以提取该文件的内容。 NodeJs中有一个内置的模块或内置库, 可以处理称为fs(文件系统)的所有读取操作。它基本上是一个JavaScript程序(fs.js), 其中编写了用于读取操作的函数。在程序中导入fs-module并使用函数从系统中的文件中读取文本。

使用功能:readFile()函数用于读取操作。

语法如下:

readFile( Path, Options, Callback)

参数:此方法接受上述和以下所述的三个参数:

  • 路径:它采用从程序到文本文件的相对路径。如果文件和程序都在同一文件夹中, 则只需提供文本文件的文件名。
  • 选项:它是一个可选参数, 用于指定要从文件中读取数据。如果未传递任何内容, 则返回默认的原始缓冲区。
  • 回调函数:它是回调函数, 具有另外两个参数(err, data)。如果操作无法提取数据, 则err将显示错误所在, 否则data参数将包含文件中的数据。

假设有文件名为Input.txt与JavaScript程序位于同一文件夹中。

Input.txt文件:

这是Input.txt文件中的一些数据。

Script.js:

<script>
// Requiring fs module in which 
// readFile function is defined.
const fs = require( 'fs' )
  
fs.readFile( 'Input.txt' , (err, data) => {
     if (err) throw err;
  
     console.log(data.toString());
})
</script>

除了使用tostring函数将缓冲区转换为文本外, 还可以直接将数据转换为文本格式。

<script>
// Requiring fs module in which
// readFile function is defined.
const fs = require( 'fs' )
  
// Reading data in utf-8 format
// which is a type of character set.
// Instead of 'utf-8' it can be 
// other character set also like 'ascii'
fs.readFile( 'Input.txt' , 'utf-8' , (err, data) => {
     if (err) throw err;
  
     // Converting Raw Buffer to text
     // data using tostring function.
     console.log(data);
})
</script>

输出如下:

This is some data inside file Input.txt.

注意:要运行脚本, 首先将两个文件放在同一个文件夹中, 然后在终端中使用NodeJs解释器运行script.js。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: