search
HomeWeb Front-endJS TutorialNode file system: fs asynchronous and synchronous (file reading and writing)

Synchronization and asynchronous

The ones with Sync in fs are synchronous and those without are asynchronous

Let’s first distinguish between synchronization and asynchronousness

Synchronous: The previous code is executed first, and the following code needs to wait for the previous code to be executed before it is executed.

Asynchronous: The code is executed in no particular order, which means that the execution of the previous code will not cause the subsequent code to block. Therefore, the order of execution results of asynchronous code is not certain.

There are two ways to operate files in fs, asynchronous and synchronous. Asynchronous is divided into ordinary asynchronous and Promise asynchronous. See the code for details.

The value and meaning of flag in options

r: 读取文件,文件不存在则报错
r+:读取并写入文件,如果文件不存在则报错
rs:以同步的方式读取文件并通知操作系忽略本地文件系统缓存。(一般不用)
w:写入文件。如果文件不存在则创建该文件,如果文件存在则覆盖
wx:作用和w类似,如果路径已存在则失败。
w+:读取并写入文件。如果文件不存在则创建该文件,如果文件存在则覆盖
wx+:和w+类型,如果路径已存在则失败。
a:追加写入文件,如果文件不存在则创建文件
ax:作用和a类型,如果路径已存在则失败。
a+: 读取并追加写入文件,如果文件不存在则创建文件
ax+:作用和a+类似,如果路径已存在则失败。

Import the module before use

let fs=require('fs');

1. Read the file

1 .readFileSync(path[, options]) Synchronously read files

path: File path

options: Optional parameters used to configure the read file options are the same

//  同步读取 需要使用一个变量来接收读取出来的数据
let data=fs.readFileSync(path,{  // path为文件的路径
		encoding:'utf8',  // 指定字符集
		flag:'r'		  // 指定读取的模式  具体上面有
});	
console.log(data.toString());   // 默认读出来的是buffer类型 使用toString()转为字符串

2. readFile(path,[,options],callback(error,data)) Normally read the file asynchronously

// 普通异步读取不需要变量 直接在回调函数中读取数据  需要注意的是:
// 回调函数接收两个参数 第一个是error 也就是异常 说明文件读取失败 如果error为null 则读取成功 data即数据
fs.readFile(path,{encoding:'utf8',flag:'r'},function(error,data){
    console.log(data.toString())
});

3. fs.promises.readFile (path[, options]) Read the file in promise mode

	// fs.promises.xxx 返回的是一个promise的对象 需要学习promise的语法 then()接收一个参数data 即数据
fs.promises.readFile(path).then(data=>{
   	console.log(data.toString());
})
// 或
let fsPromise=fs.promises.readFile(path);
fsPromise.then(data=>{
	console.log(data.toString());
})

2. Write the file

The effect of appendFile is the same as flag:'a ' in writeFile

path: The file path data is the written data option as above

1. fs.writeFileSync(file, data[, options]) Synchronously writes the file

// data为需要写入的数据 options同上 写入的方式 a+为追加写入方式
fs.writeFileSync(path,data,{flag:'a+'}); // 返回值为undefined

2. fs. appendFileSync(file, data[, options]) Synchronous append mode to write files

fs.appendFileSync(path,data,{});  // 返回值为undefined

3. fs.writeFile(file, data[, options],callback) Ordinary asynchronous writing

fs.writeFile(path,data,{flag:'a+'},function(error){
	if(err){
		console.log("写入失败");
	}else{
		console.log("写入成功");
	}})

4. fs.promises.writeFile(file, data[, options]) Promise is written asynchronously

fs.promises.writeFile(path,data,{flag:'a+'});  // 写入操作 没有返回值 也就不需要then了

5. fs.appendFile(path, data[, options], callback) Asynchronous append is written to the file

fs.appendFile(path,appendData,function(){		})

6. fs.promises.appendFile(path, data[, options]) Promise method to append written files

fs.promises.writeFile(path,data);

[Recommended: node.js video tutorial

The above is the detailed content of Node file system: fs asynchronous and synchronous (file reading and writing). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools