Table of Contents
path module
path.resolve
Get information from path
Path splicing
Splice a file and a folder
fs module
Read file status (information)
File descriptor
File reading and writing
Create a folder
Get the contents of the folder
重命名
Home Web Front-end JS Tutorial A brief analysis of common modules in node: path module and fs module

A brief analysis of common modules in node: path module and fs module

Mar 31, 2022 pm 08:34 PM
node

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!

A brief analysis of common modules in node: path module and fs module

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'
Copy after login

Then someone will use string splicing to splice.

const filePath = basePath + '/' + filename
console.log(filePath);
Copy after login

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.

A brief analysis of common modules in node: path module and fs module

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);
Copy after login

A brief analysis of common modules in node: path module and fs module

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));
Copy after login

A brief analysis of common modules in node: path module and fs module

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);
Copy after login

A brief analysis of common modules in node: path module and fs module

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'
Copy after login

A brief analysis of common modules in node: path module and fs module

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);
Copy after login

We can see the difference.

A brief analysis of common modules in node: path module and fs module

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);
Copy after login

A brief analysis of common modules in node: path module and fs module

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('后续需要执行的代码');
Copy after login

Method 3: Promise

fs.promises.stat(filepath).then(info => {
  console.log(info);
}).catch(err => {
  console.log(err);
})

console.log('后续需要执行的代码');
Copy after login

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);
  })
})
Copy after login

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);
})
Copy after login

Reading of files

fs.readFile('./abc.txt', (err, data) => {
  console.log(data);
})
Copy after login

If encoding is not filled in, the result Buffer (binary) will be returned.

A brief analysis of common modules in node: path module and fs module

fs.readFile('./abc.txt', {encoding: 'utf-8'}, (err, data) => {
  console.log(data);
})
Copy after login

A brief analysis of common modules in node: path module and fs module

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);
  })
}
Copy after login

Get the contents of the folder

fs.readdir

fs.readdir(dirname, (err, files) => {
  console.log(files);
})
Copy after login

Get all the files in the folder. The directory is as shown below, Recursion can be used.

A brief analysis of common modules in node: path module and fs module

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)
Copy after login

重命名

可以使用fs.rename对文件夹进行重命名。

fs.rename('./haha', './xixi', err => {
  console.log(err);
})
Copy after login

更多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!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
How to delete node in nvm How to delete node in nvm Dec 29, 2022 am 10:07 AM

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 use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

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!

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

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

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

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!

What to do if npm node gyp fails What to do if npm node gyp fails Dec 29, 2022 pm 02:42 PM

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.

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

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!

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

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

A brief analysis of how node implements ocr A brief analysis of how node implements ocr Oct 31, 2022 pm 07:09 PM

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!

See all articles