如何使用JavaScript读取和写入文件?
文件读取和写入操作可以使用特定的命令完成。首先必须导入执行这些操作所需的模块。所需的模块是“fs”,在Node.js中称为文件系统模块。
文件写入操作
导入文件系统文件后,调用writeFile()操作。writeFile()方法用于在JavaScript中写入文件。
语法
writeFile(path, inputData, callBackFunc)
参数
writeFile()函数接受如下三个参数。
- 路径:第一个参数是文件的路径或将输入数据写入的文件名。
- inputData:第二个参数是输入数据,包含要写入已打开文件的数据。
- callBackFunc:第三个参数是回调函数,它将错误作为参数,并在写入操作失败时显示错误。
如果文件已存在,则文件中的内容将被删除,并更新用户提供的输入;如果文件不存在,则将在给定路径中创建该文件,并将输入信息写入其中。
示例代码
以下是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") } })
输出
这不会在这里创建一个文件。如果本地运行代码,它将有效。如果打开文件,您可以看到其中写入的数据,如下所示。
The file is updated with the given data
文件读取操作
导入文件系统模块后,可以使用readFile()函数在JavaScript中读取文件。
语法
readFile(path, format, callBackFunc)
参数
readFile()函数接受如下三个参数。
- 路径:第一个参数是要读取内容的测试文件的路径。如果当前位置或目录与要打开和读取的文件所在的目录相同,则只需提供文件名。
- 格式:第二个参数是可选参数,它是文本文件的格式。格式可以是ASCII、utf-8等。
- CallBackFunc:第三个参数是回调函数,它将错误作为参数,并显示任何由于错误引起的故障。
示例代码
此代码将读取在上一个示例中填充的文件的内容并打印出来。
const fs = require('fs') fs.readFile('tp.txt', (err, inputD) => { if (err) throw err; console.log(inputD.toString()); })
输出
以下是上述示例的输出。
You are reading the content from Tutorials Point
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
读取和写入文件
以下是上述使用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()); }); });
输出
Going to write into existing file Data written successfully! Let's read newly written data Asynchronous read: Simply Easy Learning!
广告