search
HomeWeb Front-endJS TutorialNode.js file system operations

Node.js file system operations

Apr 18, 2018 pm 03:16 PM
javascriptnode.jsoperate

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])

##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!

Statement
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
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools