search
HomeWeb Front-endJS TutorialDetailed explanation of path processing module path in Node.js

Preface

In node.js, a path block is provided. In this module, many methods and attributes are provided that can be used to process and convert paths. The path Interfaces are classified according to their uses. If you think about it carefully, it will not be so confusing. Below we will introduce in detail the path processing module path in Node.js.

Get the path/file name/extension

Get the path: path.dirname(filepath)

Get the file name: path.basename(filepath )

Get the extension: path.extname(filepath)

Get the path

The example is as follows:

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
// 输出:/tmp/demo/js
console.log( path.dirname(filepath) );

Get file name

Strictly speaking, path.basename(filepath) is only the last part of the output path and does not determine whether it is a file name.

But most of the time, we can use it as a simple method of "getting the file name".

var path = require('path');
 
// 输出:test.js
console.log( path.basename('/tmp/demo/js/test.js') );
 
// 输出:test
console.log( path.basename('/tmp/demo/js/test/') );
 
// 输出:test
console.log( path.basename('/tmp/demo/js/test') );

What if you only want to get the file name, excluding the file extension? The second parameter can be used.

// 输出:test
console.log( path.basename('/tmp/demo/js/test.js', '.js') );

Get the file extension

The simple example is as follows:

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
// 输出:.js
console.log( path.extname(filepath) );

Get the file extension

The simple example is as follows:

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
// 输出:.js
console.log( path.extname(filepath) );

The more detailed rules are as follows: (assuming path.basename(filepath) === B )

Start intercepting from the last . of B until the last character.

If . does not exist in B, or the first character of B is ., then an empty string is returned.

path.extname('index.html')
// returns '.html'
 
path.extname('index.coffee.md')
// returns '.md'
 
path.extname('index.')
// returns '.'
 
path.extname('index')
// returns ''
 
path.extname('.index')
// returns ''

Path combination

path.join([...paths])
path.resolve([...paths])

path.join([...paths])

Put the paths together and then normalize them. This sentence is incomprehensible to me anyway. You can refer to the pseudocode definition below.

The example is as follows:

var path = require('path');
 
// 输出 '/foo/bar/baz/asdf'
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');

The pseudocode of path definition is as follows:

module.exports.join = function(){
 var paths = Array.prototye.slice.call(arguments, 0);
 return this.normalize( paths.join('/') );
};

path.resolve([...paths])

The description of this interface is a bit lengthy. You can imagine that you are now running the cd path command from left to right under the shell, and the absolute path/file name finally obtained is the result returned by this interface.

For example, path.resolve('/foo/bar', './baz') can be seen as the result of the following command

cd /foo/bar
cd ./baz

More comparison examples are as follows:

var path = require('path');
 
// 假设当前工作路径是 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
 
// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
console.log( path.resolve('') )
 
// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
console.log( path.resolve('.') )
 
// 输出 /foo/bar/baz
console.log( path.resolve('/foo/bar', './baz') );
 
// 输出 /foo/bar/baz
console.log( path.resolve('/foo/bar', './baz/') );
 
// 输出 /tmp/file
console.log( path.resolve('/foo/bar', '/tmp/file/') );
 
// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path/www/js/mod.js
console.log( path.resolve('www', 'js/upload', '../mod.js') );

Path parsing

path.parse(path)

path.normalize(filepath)

From the description of the official document, path.normalize (filepath) should be a relatively simple API, but I always feel unsure when using it.

why? The API description is too brief and includes the following:

If the path is empty, return., which is equivalent to the current working path.

Merge repeated path separators (such as / under Linux) in the path into one.

Process the ., .. in the path. (Similar to cd in the shell..)

If there is a / at the end of the path, then keep the /.

In other words, path.normalize is "What is the shortest path I can take that will take me to the same place as the input"

The code example is as follows. It is recommended that readers copy the code and run it to see the actual effect.

var path = require('path');
var filepath = '/tmp/demo/js/test.js';
 
var index = 0;
 
var compare = function(desc, callback){
 console.log('[用例%d]:%s', ++index, desc);
 callback();
 console.log('\n');
};
 
compare('路径为空', function(){
 // 输出 .
 console.log( path.normalize('') );
});
 
compare('路径结尾是否带/', function(){
 // 输出 /tmp/demo/js/upload
 console.log( path.normalize('/tmp/demo/js/upload') );
 
 // /tmp/demo/js/upload/
 console.log( path.normalize('/tmp/demo/js/upload/') );
});
 
compare('重复的/', function(){
 // 输出 /tmp/demo/js
 console.log( path.normalize('/tmp/demo//js') );
});
 
compare('路径带..', function(){
 // 输出 /tmp/demo/js
 console.log( path.normalize('/tmp/demo/js/upload/..') );
});
 
compare('相对路径', function(){
 // 输出 demo/js/upload/
 console.log( path.normalize('./demo/js/upload/') );
 
 // 输出 demo/js/upload/
 console.log( path.normalize('demo/js/upload/') );
});
 
compare('不常用边界', function(){
 // 输出 ..
 console.log( path.normalize('./..') );
 
 // 输出 ..
 console.log( path.normalize('..') );
 
 // 输出 ../
 console.log( path.normalize('../') );
 
 // 输出 /
 console.log( path.normalize('/../') );
  
 // 输出 /
 console.log( path.normalize('/..') );
});

File path decomposition/combination

path.format(pathObject): Combine the root, dir, base, name, and ext attributes of pathObject into one according to certain rules. file path.

path.parse(filepath): The reverse operation of the path.format() method.

Let’s first take a look at the official website’s description of related attributes.

First under linux

┌─────────────────────┬────────────┐
│   dir  │ base │
├──────┬    ├──────┬─────┤
│ root │    │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
(all spaces in the "" line should be ignored -- they are purely for formatting)

Then under windows

┌─────────────────────┬────────────┐
│   dir  │ base │
├──────┬    ├──────┬─────┤
│ root │    │ name │ ext │
" C:\  path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
(all spaces in the "" line should be ignored -- they are purely for formatting)

path.format(pathObject)

After reading the relevant API document description, I found out , in path.format(pathObject), the configuration properties of pathObject can be further streamlined.

According to the description of the interface, the following two are equivalent.

Root vs dir: The two can be replaced with each other. The difference is that when the paths are spliced, / will not be automatically added after root, but dir will.

base vs name+ext: The two can be replaced with each other.

var path = require('path');
 
var p1 = path.format({
 root: '/tmp/', 
 base: 'hello.js'
});
console.log( p1 ); // 输出 /tmp/hello.js
 
var p2 = path.format({
 dir: '/tmp', 
 name: 'hello',
 ext: '.js'
});
console.log( p2 ); // 输出 /tmp/hello.js

path.parse(filepath)

For the reverse operation of path.format(pathObject), go directly to the official website for examples.

The four properties are very convenient for users, but path.format(pathObject) also has four configuration properties, which is a bit easy to confuse.

path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }

Get the relative path

Interface: path.relative(from, to)

Description: The relative path from the from path to the to path.

Boundary:

If from and to point to the same path, then an empty string is returned.

If either from or to is empty, then return the current working path.

The above example:

var path = require('path');
 
var p1 = path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
console.log(p1); // 输出 "../../impl/bbb"
 
var p2 = path.relative('/data/demo', '/data/demo');
console.log(p2); // 输出 ""
 
var p3 = path.relative('/data/demo', '');
console.log(p3); // 输出 "../../Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path"

Platform-related interfaces/properties

The following properties and interfaces are related to the specific implementation of the platform. In other words, the same attributes and interfaces behave differently on different platforms.

Path.posix: Linux implementation of path-related attributes and interfaces.

Path.win32: Win32 implementation of path-related attributes and interfaces.

path.sep: path separator. On linux it is /, on windows it is ``.

    path.delimiter:path设置的分割符。linux上是:,windows上是;。

注意,当使用 path.win32 相关接口时,参数同样可以使用/做分隔符,但接口返回值的分割符只会是``。

直接来例子更直观。

> path.win32.join('/tmp', 'fuck')
'\\tmp\\fuck'
> path.win32.sep
'\\'
> path.win32.join('\tmp', 'demo')
'\\tmp\\demo'
> path.win32.join('/tmp', 'demo')
'\\tmp\\demo'

path.delimiter

linux系统例子:

console.log(process.env.PATH)
// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
 
process.env.PATH.split(path.delimiter)
// returns ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

windows系统例子:

console.log(process.env.PATH)
// 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
 
process.env.PATH.split(path.delimiter)
// returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用node.js能有所帮助,如果有疑问大家可以留言交流,谢谢大家对PHP中文网的支持。

更多Node.js中路径处理模块path详解相关文章请关注PHP中文网!

Statement
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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function