The core module of Node.js - path


What is path?

path is the core module of Node.js, which is specially used to process file paths. The path module provides a series of practical functions and APIs for processing file paths.

How to use path?

Here we mainly introduce some common APIs of the path module.

//引入path模块,commonjs规范
const path = require('path');
//定义一个具体的文件路径
const filePath = '/home/user/Documents/report.txt';


//拼接路径:path.join()方法可以将多个路径片段拼接成一个完整的路径,避免手动拼接过程中出现错误
const fullPath = path.join('/home', 'user', 'Documents', 'report.txt');
console.log(fullPath); // 输出: /home/user/Documents/report.txt
//解析路径:path.resolve()方法可以根据相对路径和当前执行脚本所在的绝对路径来解析出完整的绝对路径。
const absolutePath = path.resolve('index.js');
console.log(absolutePath); // 输出: /home/user/project/index.js
//提取路径信息:path.dirname()、path.basename()和path.extname()等方法可方便地获取路径的目录名、基础文件名和扩展名。
const dirName = path.dirname(fullPath);
console.log(dirName); // 输出: /home/user/Documents

const baseName = path.basename(fullPath);
console.log(baseName); // 输出: report.txt

const extName = path.extname(fullPath);
console.log(extName); // 输出: .txt


in conclusion

The path module of Node.js is an essential tool for processing file paths, providing functions such as normalization, splicing, parsing, and extraction of path information. Understanding and proficiently using the API of the path module can greatly improve the efficiency and accuracy of file path processing. Whether building web applications, file operations, or other Node.js projects, the path module can save developers a lot of time and effort

Guess you like

Origin blog.csdn.net/Wustfish/article/details/132203073