Share some Nodejs common file fs module API (summary)
This article organizes and records some Nodejs file fs module API commonly used in work, so as not to forget it next time.
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; }); })
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) })
Read directory:fs.readdir(path:string,callback:(err , files:Array<string>)=>void)
fs.readdir("./dir",(err,fileNames)=>{ console.log(fileNames) })
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; }); })
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('message.txt', data, (err) => { if (err) throw err; });
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; }); })
Delete file (directory)
Delete files: fs.unlink(path, callback:(err)=>void)
Delete directories: fs.rmdir(path, callback:(err)=> ;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() })
Rename
Renaming includes renaming files and directories
//文件 fs.rename('oldFile.txt', 'newFile.txt', (err) => { if (err) throw err; console.log('Rename complete!'); }); //目录 fs.rename('oldFileDir', 'newFileDir', (err) => { if (err) throw err; console.log('Rename complete!'); });
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!

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

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

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



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.

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.

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.

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

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.

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.

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

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.
