JavaScript读写文本文件
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 t
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 provide the name of the file only. If the file does not exist then the new file will be created automatically.
路径:路径是文本文件的位置。 如果要在与程序相同的文件夹中生成文件,请仅提供文件名。 如果该文件不存在,则将自动创建新文件。
Data: Second is Data in This parameter we need to pass info that is required to write in the file.
数据:第二个是数据输入。此参数中,我们需要传递写入文件所需的信息。
Callback: Last one is the Callback Function in this we pass error string. If the operation fails to write the data, an error shows the fault.
回调:最后一个是回调函数,在此我们传递错误字符串。 如果操作无法写入数据,则错误将显示故障。
index.js
index.js
<script>
// import fs module in which writeFile function is defined.
const fsLibrary = require('fs')
// Data which will need to add in a file.
let data = "Hello world."
// Write data in 'newfile.txt' .
fsLibrary.writeFile('newfile.txt', data, (error) => {
// In case of a error throw err exception.
if (error) throw err;
})
</script>
To run above code run this command:
要运行以上代码,请运行以下命令:
>node index.js
>节点index.js
readFile:
readFile:
It is used to read the content of the file. its syntax is:
它用于读取文件的内容。 它的语法是:
readFile(Path, Options, Callback)
It also has three parameters path, callback, options.
它还具有三个参数路径,回调,选项。
path is a location of Text File. If both file and program are in a similar folder, then directly give the file name of the text file.
path是文本文件的位置。 如果文件和程序都位于相似的文件夹中,则直接提供文本文件的文件名。
Second option which specifies the data is to be gathered from the file and it is optional. If you pass nothing then it returns raw buffer.
第二个选项指定要从文件中收集数据,它是可选的。 如果您不传递任何内容,则它将返回原始缓冲区。
The last one is Callback function which has two more parameters (error, txtString). If at any instance it fails to load or read the file then it returns error or exception otherwise it returns all data of the file.
最后一个是回调函数,它具有另外两个参数(错误,txtString)。 如果在任何情况下都无法加载或读取文件,则返回错误或异常,否则返回文件的所有数据。
index.js
index.js
<script>
// import fs module in which readFile function is specified.
const fsLibrary = require('fs')
fsLibrary.readFile('ind.txt', (error, txtString) => {
if (error) throw err;
console.log(txtString.toString());
})
</script>
To run this program enter below command:
要运行此程序,请输入以下命令:
>node index.js
>节点index.js
方法2:使用ActiveXObject (Method 2: Using ActiveXObject)
Another method is by using a web page ActiveX objects but this method is mainly work in Internet Explorer only.
另一种方法是使用网页ActiveX对象,但是该方法主要仅在Internet Explorer中有效。
This ActiveXObject is used to return an instance of a file system library which is used with the CreateTextFile method. This JS method which generates a file defined functions and states a TextStream object to read from or write to the file. It also returns a boolean value on the basis of this we can find out that we can overwrite to the current file or not. So, if you want to add the data to the created file you can use writeline method which is used to add text string to the file.
此ActiveXObject用于返回与CreateTextFile方法一起使用的文件系统库的实例。 此JS方法生成文件定义的函数并声明TextStream对象以从文件读取或写入文件。 基于此,它还会返回一个布尔值,我们可以发现是否可以覆盖当前文件。 因此,如果要将数据添加到创建的文件中,可以使用writeline方法,该方法用于将文本字符串添加到文件中。
Using ActiveX objects, the following should be included in your code to read a file:
使用ActiveX对象,以下内容应包含在代码中以读取文件:
var ActivexObj = new ActiveXObject(libraryname.classname[, location])
The ActiveX object contains three things libraryname, classname, location. So, classname is the instance of a class that needs to be created. libraryname is a mandatory field and it is the sign of the app giving the object.
ActiveX对象包含三个名称库名称,类名称和位置。 因此,类名是需要创建的类的实例。 libraryname是必填字段,它是应用程序提供对象的标志。
To open a new file:
要打开一个新文件:
let newfile = new ActiveXObject("Scripting.FileSystemObject");
let openFile = newfile.OpenTextFile("C:\\testfile.txt", 1, true);
Write data to a file:
将数据写入文件:
var editFile = newfile.CreateTextFile("c:\\Demofile.txt", true);
editFile.WriteLine("Add sample text to the file...");
editFile.WriteLine('steadyAdvice');
editFile.Close();
方法3:使用PHP (Method 3: Using PHP)
Another approach is by using php. In this, we use some inbuilt javascript functions for reading and writing data to the files. These are some functions fopen(), fread() and fwrite() that we use here.
另一种方法是使用php。 在此,我们使用一些内置的javascript函数来将数据读取和写入文件。 这些是我们在这里使用的一些函数fopen(),fread()和fwrite()。
The function fopen() takes two arguments:
函数fopen()有两个参数:
Path and Mode (0 for reading & 3 for writing).
路径和模式(0用于读取,3用于写入)。
The fopen() function returns -1 if the file is successfully opened.
如果文件成功打开,则fopen()函数将返回-1。
Example:
例:
To open a file use fopen method:
要打开文件,请使用fopen方法:
openFile=fopen(getFilePath(),0);
To read the file content use fread() function:
要读取文件内容,请使用fread()函数:
readString = fread(openFile,flength(file) ;
To write the contents to the file use fwrite() function :
要将内容写入文件,请使用fwrite()函数:
editFile = fopen("c:\MyNewFile.txt", 3);// opens the file for writing
fwrite(file, str);// str is the content that is to be written into the file.
Comment down below if you have any queries regarding how to read and write to text file in JavaScript.
如果您对如何在JavaScript中读取和写入文本文件有任何疑问,请在下面注释掉。
翻译自: https://www.thecrazyprogrammer.com/2019/12/javascript-read-and-write-to-text-file.html
更多推荐



所有评论(0)