


A brief analysis of common modules in node: path module and fs module
There are many built-in objects in node, which can help us perform many operations, including operations on paths, files, etc. The following article will introduce to you the path module and fs module among the commonly used built-in modules of node. I hope it will be helpful to you!
path module
The path module is used to process paths and files and provides many methods.
path.resolve
There is a requirement to concatenate the path and file name.
const basePath = '/user/why' const filename = 'abc.txt'
Then someone will use string splicing to splice.
const filePath = basePath + '/' + filename console.log(filePath);
Although there is no problem with this result, considering different systems, Windows systems can use \ or \\ or / as path separators, while Mac OS and Linux Unix operating systems use / as path separators. symbol.
To solve the above problem, we can use path.resolve to splice paths.
const path = require('path') const basePath = '/user/why' const filename = 'abc.txt' const filePath = path.resolve(basePath, filename) console.log(filePath);
Get information from path
- dirname: Get the parent folder of the file
- basename: Get file name
- extname: Get file extension
const path = require('path') const filePath = '/User/haha/abc.txt' console.log(path.dirname(filePath)); console.log(path.basename(filePath)); console.log(path.extname(filePath));
Path splicing
If we want to splice multiple paths, but different operating systems may use different separators, we can use the path.join function.
const path = require('path') const basepath = '/User/haha' const filename = 'abc.txt' const filePath = path.join(basepath, filename) console.log(filePath);
Splice a file and a folder
If we want to splice a file and a folder, we can Use path.resolve.
const basepath = 'User/haha' const filename = 'abc.txt'
path.resolve and path.join can also be used to splice paths, so what is their difference?
const basepath = '../User/haha' const filename = './abc.txt' const othername = './haha.js' const filePath1 = path.join(basepath, filename, othername) console.log(filePath1); const filePath2 = path.resolve(basepath, filename, othername) console.log(filePath2);
We can see the difference.
fs module
nodejs Most file system APIs provide three operating methods:
Synchronous file operation: the code will be blocked and will not continue to execute
Asynchronous callback function file operation: the code will not be blocked and a callback needs to be passed in function, when the result is obtained, the callback function executes
Asynchronous Promise operation file: the code will not be blocked. Calling method operation through fs.promises will return a Promise, which can be passed then , catch for processing.
Read file status (information)
Method 1 synchronization operation: fs.statSync
const fs = require('fs') const filepath = './abc.txt' const info = fs.statSync(filepath) console.log('后续需要执行的代码'); console.log(info);
Method 2 asynchronous operation
fs.stat(filepath, (err, info) => { if(err) { console.log(err); return } console.log(info); console.log(info.isFile()); // 判断是否是一个文件 console.log(info.isDirectory()); // 判断是否是一个文件夹 }) console.log('后续需要执行的代码');
Method 3: Promise
fs.promises.stat(filepath).then(info => { console.log(info); }).catch(err => { console.log(err); }) console.log('后续需要执行的代码');
File descriptor
node is allocated for all open files A file descriptor of type numeric. All file system operations use these file descriptors to identify and track each specific file.
fs.open() method is used to allocate a new file descriptor fd. Once allocated, the file descriptor can be used to read data from the file, write data to the file, or request information about the file.
const fs = require('fs') fs.open('./abc.txt', (err, fd) => { if(err) { console.log(err); return } // 通过文件描述符去获取文件信息 fs.fstat(fd, (err, info) => { console.log(info); }) })
File reading and writing
fs.readFile(path[, options], callback): Read file content
fs.writeFile( path[, options], callback): Write content to the file
option parameters:
flag: Writing method
encoding: Character encoding
Writing of files
fs.writeFile('./abc.txt', content, {flag: "a"}, err => { console.log(err); })
Reading of files
fs.readFile('./abc.txt', (err, data) => { console.log(data); })
If encoding is not filled in, the result Buffer (binary) will be returned.
fs.readFile('./abc.txt', {encoding: 'utf-8'}, (err, data) => { console.log(data); })
Create a folder
Use fs.mkdir() or fs.mkdirSync Create a new folder.
const fs = require('fs') // 创建文件夹 const dirname = './haha' if(!fs.existsSync(dirname)) { fs.mkdir(dirname, (err) => { console.log(err); }) }
Get the contents of the folder
fs.readdir
fs.readdir(dirname, (err, files) => { console.log(files); })
Get all the files in the folder. The directory is as shown below, Recursion can be used.
const fs = require('fs') const path = require('path') const dirname = './haha' function getFiles(dirname) { fs.readdir(dirname, {withFileTypes: true}, (err, files) => { // console.log(files); for(let file of files) { // 判断是否是文件夹 if(file.isDirectory()) { const filepath = path.resolve(dirname, file.name) getFiles(filepath) } else { console.log(file.name); } } }) } getFiles(dirname)
重命名
可以使用fs.rename对文件夹进行重命名。
fs.rename('./haha', './xixi', err => { console.log(err); })
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of A brief analysis of common modules in node: path module and fs module. 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











How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

npm node gyp fails because "node-gyp.js" does not match the version of "Node.js". The solution is: 1. Clear the node cache through "npm cache clean -f"; 2. Through "npm install -g n" Install the n module; 3. Install the "node v12.21.0" version through the "n v12.21.0" command.

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

How to implement OCR (optical character recognition)? The following article will introduce to you how to use node to implement OCR. I hope it will be helpful to you!
