Node.js file system operations
This time I will bring you Node.jsFile systemoperation, what are the notes of 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)
The asynchronous method returns the operation result as the parameter of the callback function. 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) })
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){ //回调函数代码 })
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){ //回调函数代码 })
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){ //回调函数代码略 } //第一个参数为读取文件操作失败时触发的错误对象 第二个参数值为读取到的文件内容
When reading a file using the synchronous method, use the readFileSync method:
var data = fs.readFileSync(filename,[options])
eg:
var fs = require('fs') try{ var data = fs.readFileSync('./text.txt','utf8') //在控制台中输出文件内容 console.log(data) }catch(ex){ console.log('读取文件时发生错误') }
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){ //回调函数代码 }
When writing files synchronously, use the writeFileSync method:
fs.writeFileSync(filename,data,[options])
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])
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){ //回调函数代码 } //第一个参数为打开文件操作失败时所触发的错误对象, 第二个参数为一个整数值,代表打开文件时返回的文件描述符
When opening a file synchronously, use the openSync method:
var fd = fs.openSync(filename,flag,[mode])
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:被读取的缓存区对象
When opening a file synchronously, use the readSync method:
var byteRead = fs.readSync(fd,buffer,offset,length,position)
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 })
When writing files synchronously, use the writeSync method
fs.writeSync(fd,buffer,offset,length,position)
In the fs module, use the close method and closeSync method to close the file
fs.close(fd,[callbcak]) fs.closeSync(fd)
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])
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

Ele.me is a software that brings together a variety of different delicacies. You can choose and place an order online. The merchant will make it immediately after receiving the order. Users can bind WeChat through the software. If you want to know the specific operation method , remember to check out the PHP Chinese website. Instructions on how to bind WeChat to Ele.me: 1. First open the Ele.me software. After entering the homepage, we click [My] in the lower right corner; 2. Then in the My page, we need to click [Account] in the upper left corner; 3. Then come to the personal information page where we can bind mobile phones, WeChat, Alipay, and Taobao. Here we click [WeChat]; 4. After the final click, select the WeChat account that needs to be bound in the WeChat authorization page and click Just [Allow];

PHP String Operation: A Practical Method to Effectively Remove Spaces In PHP development, you often encounter situations where you need to remove spaces from a string. Removing spaces can make the string cleaner and facilitate subsequent data processing and display. This article will introduce several effective and practical methods for removing spaces, and attach specific code examples. Method 1: Use the PHP built-in function trim(). The PHP built-in function trim() can remove spaces at both ends of the string (including spaces, tabs, newlines, etc.). It is very convenient and easy to use.

1. Introduction to PDO PDO is an extension library of PHP, which provides an object-oriented way to operate the database. PDO supports a variety of databases, including Mysql, postgresql, oracle, SQLServer, etc. PDO enables developers to use a unified API to operate different databases, which allows developers to easily switch between different databases. 2. PDO connects to the database. To use PDO to connect to the database, you first need to create a PDO object. The constructor of the PDO object receives three parameters: database type, host name, database username and password. For example, the following code creates an object that connects to a mysql database: $dsn="mysq
