Node.js file system operations

php中世界最好的语言
Release: 2018-04-18 15:16:38
Original
1502 people have browsed it

This time I will bring you Node.jsFile systemoperation, what are thenotesof Node.js file system operation, the following is a practical case, let's take a look.

1. Synchronous methods and asynchronous methods

In Node.js, use the fs module to implement all related file and directory creation, writing and deletion operations. , in the fs module, all operations on files and directories can use both synchronous and asynchronous methods. The difference between the two is: the synchronization method returns the operation result immediately, and subsequent code cannot be executed before the operation performed using the synchronization method is completed. The code is similar to the following:

Var fs = require('fs') var data = fs.readFileSysnc('./index.html','utf8') //等待操作返回结果,然后利用该结果 console.log(data)
Copy after login

The asynchronous method returns the operation result as the parameterof the callbackfunction. After the method call, the subsequent code can be executed immediately. The code is as follows:

var fs = require('fs') fs.readFile('./index.html','utf8'.function(err,data){ //操作结果作为回调函数的第二个参数返回 console.log(data) })
Copy after login

In addition, when multiple asynchronous methods are called using the method shown below, the order in which the operation results are returned is not guaranteed

fs.readFile('./file.html',function(err,data){ //回调函数代码 }) fs.readFile('./otrher.html',function(err,data){ //回调函数代码 })
Copy after login

In the above code, we perform read operations on two files at the same time, but we do not ensure which operation result is returned first. If we want to ensure that two files are read after one quote is read, we should use the following method:

fs.readFileSync('./file.html',function(err,data){ //回调函数代码 }) fs.readFileSync('./otrher.html',function(err,data){ //回调函数代码 })
Copy after login

2. Perform read and write operations on files

2.1 Complete reading and writing of files

You can use the readFile method or readFileSync method to read a file completely:

fs.readFile(filename,[options],callback) //第一个参数:必选指定读取文件的完整文件路径及文件名 第二个参数:指定读取文件时需要使用的选项,在该参数值对象中可以使用flag属性指定对该文件采取什么操作,默认为‘r' option: flag'r':读取文件,如果文件不存在则抛出异常 'r+':读取并写入文件,如果文件不存在则抛出异常 'rs':以同步方式读取文件并通知操作系统忽略本地文件系统缓存,如果文件不存在则抛出异常。因为本属性值忽略本地缓存,适用于操作网络文件系统,但由于其对性能产生一定的负面影响,不建议在其他环境下使用 'w':写入文件,如果文件不存在则创建文件,如果文件存在则清空文件内容 'wx':作用与'w'类似,但以排他方式写入文件 'w+':读取并写入文件。如果不存在则创建文件,如果该文件已存在则清空文件内容 'wx+':作用与'w+'类似,但是以排他方式写入文件 'a':追加写入文件,如果文件不存在则创建文件 'ax':作用与'a+'类似,但是以排他方式打开文件 encoding: utf8,ascii,base64, callback(err,data){ //回调函数代码略 } //第一个参数为读取文件操作失败时触发的错误对象 第二个参数值为读取到的文件内容
Copy after login

When reading a file using the synchronous method, use the readFileSync method:

var data = fs.readFileSync(filename,[options])
Copy after login

eg:

var fs = require('fs') try{ var data = fs.readFileSync('./text.txt','utf8') //在控制台中输出文件内容 console.log(data) }catch(ex){ console.log('读取文件时发生错误') }
Copy after login

When writing a file completely, use the writeFile method or writeFileSync method in the fs module

fs.writeFile(filename,datda,[options],callback) //第一个参数:用于指定被写入文件的完整文件路径及文件名 第二个参数:用于指定需要写入的内容,参会素可以为一个字符串或一个Buffer对象 第三个参数:指定写入文件时需要的选项 flag属性:用于指定该文件采用何种操作,默认为'w' mode属性:指定当文件被打开时对文件的读写权限,默认为0666(可读写),第一位必须为0,第二位用于规定文件或目录所有者的权限,第三位为文件或目录所属用户组的权限,第四位为其他用户权限 1:执行权限 2:写权限 4:读权限 encoding属性:指定使用何种编码格式来写入文件,:utf8 ascii base64 callback(err){ //回调函数代码 }
Copy after login

When writing files synchronously, use the writeFileSync method:

fs.writeFileSync(filename,data,[options])
Copy after login

When appending a string or data in a buffer to the bottom of a file, you can use the appendFile or appendFildSync method in the fs module

fs.appendFile(filname,data,[options],callback) fs.appendFileSync(filename,data[options])
Copy after login

2.2 Start reading and writing files from the specified location

First, you need to use the open method or openSync method in the fs module to open the file,

fs.open(filename,flags,[mode],callback) 其中callback参数为:function(err,fd){ //回调函数代码 } //第一个参数为打开文件操作失败时所触发的错误对象, 第二个参数为一个整数值,代表打开文件时返回的文件描述符
Copy after login

When opening a file synchronously, use the openSync method:

var fd = fs.openSync(filename,flag,[mode])
Copy after login

After opening the file, you can use the read method or readSync method in the fs module in the callback function to read the file from the specified location of the file, or you can use the write method or writeSync method in the fs module to start writing from the specified location of the file. data

First introduce the read method:

fs.read(fd,buffer,offset,length,position,callback) //第一个参数:open方法所所使用的回调函数中返回的文件描述符或openSync方法返回的文件描述符; 第二个参数:英语指定将文件数据读取到哪个缓存区; 第三个参数:整数,用于指定向缓存区中写入数据时的开始位置,以字节为单位 第四个参数:整数,指定从文件中读取的字节数 第五个参数:整数,指定读取文件时开始位置 callback(err,bytesRead,buffer){ //回调函数代码 } err:读取文件操作失败时触发的错误对象 bytesRead实际读取的字节数 buffer:被读取的缓存区对象
Copy after login

When opening a file synchronously, use the readSync method:

var byteRead = fs.readSync(fd,buffer,offset,length,position)
Copy after login

After opening the file, use the write method or writeSync method in the fs module to read data from a buffer and start ingesting the data from the specified point in the file

fs.write(fd,buffer,offset,length,position,callback) 其中callback为function(err,written,buffer){ //回调函数代码 } eg: 1 var fs = require('fs') 2 var buf = new Buffer('我喜欢编程') 3 fs.open('./message.txt','w',function(err,fd){ 4 fs.write(fd,buf,3,9,0,function(err,written,buffer){ 5 if(err)console.log("写文件操作失败") 6 console.log("写文件操作成功") 7 }) 8 })
Copy after login

When writing files synchronously, use the writeSync method

fs.writeSync(fd,buffer,offset,length,position)
Copy after login

In the fs module, use the close method and closeSync method to close the file

fs.close(fd,[callbcak]) fs.closeSync(fd)
Copy after login

Before calling the Close method, you can use the FSYN method to write all the contents of the cache area into the file to prevent the omissions from appearing

fs.fsyn(fd,[callback])
Copy after login

##zhi believe it. Pay attention to other related articles on php Chinese website!

Recommended reading:

Combining HTML tags with DOM nodes

Summary of JS implicit type conversion

The above is the detailed content of Node.js file system operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!