Table of Contents
Synchronization and asynchronous
Open and close files
Read the file (directory)
Write the file
Delete file (directory)
View the status information of the directory (file)
Rename
Finally
Home Web Front-end JS Tutorial Share some Nodejs common file fs module API (summary)

Share some Nodejs common file fs module API (summary)

Aug 12, 2021 am 09:56 AM
nodejs File system

This article organizes and records some Nodejs file fs module API commonly used in work, so as not to forget it next time.

Share some Nodejs common file fs module API (summary)

As a web development engineer, it is inevitable to deal with Nodejs. The fs module is very useful and can perform some file-related operations, but I always forget it. , Forgot to remember. I plan to organize and record it again today to avoid forgetting it next time.

Synchronization and asynchronous

The file operations of the fs module generally support both synchronous and asynchronous APIs, and asynchronous also includes callback functions and promsie forms. Synchronization is usually followed by the words sync. [Recommended learning: "nodejs Tutorial"]

Open and close files

fs.open(path:string,callback: (err,fd)=>void) is used to open a file, obtain the file descriptor (file descriptor), and perform file operations based on the obtained file descriptor. fs.close(fd:number,callback:(err)=>void) Used to close the file

//打开文件
fs.open(path,(err,fd)=>{
    //针对拿到的fd 进行操作
    
    //关闭文件
    fs.close(fd, (err) => {
        if (err) throw err;
    });
})
Copy after login

Generally used to perform various operations on files. If you only want to read the contents of the file, it is recommended to use fs.readFile

Read the file (directory)

Read the file:fs.readFile(path:string,callback:(err,data)=>void)

fs.readFile(path,(err,data)=>{
    //string或者buffer
    console.log(data)
})
Copy after login

Read directory:fs.readdir(path:string,callback:(err , files:Array<string>)=>void)

fs.readdir("./dir",(err,fileNames)=>{
    console.log(fileNames)
})
Copy after login

There is another way to read through the file descriptor:

fs.read(fd, buffer,offset,length,position,callback:(err,bytesLen,buffer)=>void)

//分配一块长度为10的缓存区
const buffer = Buffer.alloc(10);
//打开文件
fs.open(path,(err,fd)=>{
    //针对拿到的fd 进行操作:将fd对应的文件内容读取到buffer里
    //position为文件的起点
    //length为读取的长度
    //offset为缓存区起读的位置
    fs.read(fd,buffer,offset,length,position,(err,bytesLen,buffer)=>{
        //buffer为包含读到数据的原始buffer对象
        //bytesLen === length;// true
    })
    //关闭文件
    fs.close(fd, (err) => {
        if (err) throw err;
    });
})
Copy after login

Write the file

Write the data Enter the file, the data can be string or buffer:fs.writeFile(path,data,callback:(err)=>void)

fs.writeFile(&#39;message.txt&#39;, data, (err) => {
  if (err) throw err;
});
Copy after login

There is another way to write a file through the file descriptor fd:

fs.open(path,(err,fd)=>{
    //针对拿到的fd 进行操作:将buffer内容写如fd对应的文件里
    //position为文件的起点
    //length为待写的长度
    //offset为缓存区起写的位置
    fs.write(fd,buffer,offset,length,position,(err,bytesWrittenLen,buffer)=>{

    })
    //关闭文件
    fs.close(fd, (err) => {
        if (err) throw err;
    });
})
Copy after login

Delete file (directory)

Delete files: fs.unlink(path, callback:(err)=>void)

Delete directories: fs.rmdir(path, callback:(err)=&gt ;void)

Supports deleting directories and files at the same time: fs.rm(path,callback:(err)=>void)

View the status information of the directory (file)

fs.stat(path,(err,stat)=>{
    //stat包含了该目录或文件的大小、创建时间、更新时间,是目录还是文件等
    //stats.isDirectory()
    //stats.isFile()
})
Copy after login

Rename

Renaming includes renaming files and directories

//文件
fs.rename(&#39;oldFile.txt&#39;, &#39;newFile.txt&#39;, (err) => {
  if (err) throw err;
  console.log(&#39;Rename complete!&#39;);
});
//目录
fs.rename(&#39;oldFileDir&#39;, &#39;newFileDir&#39;, (err) => {
  if (err) throw err;
  console.log(&#39;Rename complete!&#39;);
});
Copy after login

Finally

Thank you for reading. If you have any questions, please leave a message for discussion. Thank you!

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Share some Nodejs common file fs module API (summary). For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

See all articles