如何使用 Javascript 读写文件?

javascriptweb developmentfront end technology

可以使用一些命令对文件进行读写操作。但执行这些操作所需的模块必须导入。所需模块是"fs",在 JavaScript 中称为文件系统模块。

对文件进行写入操作

导入文件系统文件后,将调用 writeFile() 操作。在 JavaScript 中,使用 writeFile() 方法将数据写入文件。该方法的语法如下 −

writeFile(path,inputData,callBackFunction)

writeFile() 函数接受三个参数 −

  • Path − 第一个参数是要写入输入数据的文件的路径或文件的名称。

    如果已经有一个文件,则删除文件中的内容并更新用户提供的输入,或者如果文件不存在,则将在给定路径中创建该文件并将输入信息写入其中。

  • inputData − 第二个参数是输入数据,其中包含要写入打开的文件中的数据。

  • callBackFuntion −第三个参数是回调函数,该函数以错误为参数,如果写入操作失败则显示错误。

示例 1

以下是 JavaScript 中文件写入操作的示例。

const fs = require('fs') let fInput = "You are reading the content from Tutorials Point" fs.writeFile('tp.txt', fInput, (err) => { if (err) throw err; else{ console.log("The file is updated with the given data") } })

如果打开输入文件,您可以观察到其中写入的数据,如下所示 -

从文件中读取

导入文件系统模块后,可以使用 readFile() 函数读取 JavaScript 中的文件。

语法

从文件中读取的语法如下 -

readFile(path, format, callBackFunc)

readFile() 函数接受三个参数,包括一个可选参数。

  • 路径 -第一个参数是要从中读取内容的测试文件的路径。如果当前位置或目录与要打开和读取的文件所在的目录相同,则只需提供文件名。

  • 格式 - 第二个参数是可选参数,即文本文件的格式。格式可以是 ASCII、utf-8 等。

  • CallBackFunc - 第三个参数是回调函数,它将错误作为参数并显示由于错误而引发的任何故障。

示例 2

以下示例尝试读取上一个示例中填充的文件的内容并将其打印出来 -

const fs = require('fs') fs.readFile('tp.txt', (err, inputD) => { if (err) throw err; console.log(inputD.toString()); })

输出

以下是上述示例的输出 −

您正在阅读来自教程点的内容

控制台中显示的文本是给定文件中的文本。

示例 3

以下是使用 node.js 上的 fs 模块读取和写入文件的组合示例。让我们创建一个名为 main.js 的 JS 文件,其中包含以下代码 −

var fs = require("fs"); console.log("Going to write into existing file"); // Open a new file with name input.txt and write Simply Easy Learning! to it. fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) { console.log("Data written successfully!"); console.log("Let's read newly written data"); // Read the newly written file and print all of its content on the console fs.readFile('input.txt', function (err, data) { console.log("Asynchronous read: " + data.toString()); }); });

相关文章