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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),