In this tutorial, I will tell you about how you can read and write to text file using JavaScript. As we know JavaScript does not have the ability to access the user’s file system so for this we need to run the project on a server. To implement this we use node.js.
在本教程中,我将向您介绍如何使用JavaScript读写文本文件。 众所周知,JavaScript无法访问用户的文件系统,因此我们需要在服务器上运行项目。 为了实现这一点,我们使用node.js。
In node.js these are one library fs (File-System) which is used to manage all read and write operations. By using the fs module we can read and write files in both synchronous and asynchronous way.
在node.js中,这些是一个fs(文件系统)库,用于管理所有读取和写入操作。 通过使用fs模块,我们可以同步和异步方式读取和写入文件。
There are many ways in which we can read and write data to file. Lets have a look on each of them one by one.
我们可以通过多种方式读取和写入文件数据。 让我们一一看一下。
JavaScript读写文本文件 (JavaScript Read and Write to Text File)
方法1:使用Node.js (Method 1: Using Node.js)
First is by using writefile and readFile method in node.js environment.
首先是在node.js环境中使用writefile和readFile方法。
writeFile:
writeFile:
This is used to write content to file. Its syntax is below:
这用于将内容写入文件。 其语法如下:
writeFile(Path, Data, Callback)
It has three parameters path, data, callback.
它具有三个参数路径,数据,回调。
Path: The path is the location of Text File. If the file is to be generated in the same folder as that of the program, then pro