search
HomeWeb Front-endJS TutorialIntroduction to path processing module path in Node.js

Introduction to path processing module path in Node.js

Jun 30, 2018 am 10:07 AM
nodenodejspathpath modulemodulemodule path

This article mainly introduces the path processing module path in Node.js. It has certain reference value. Now I share it with you. Friends in need can refer to it.

I believe everyone knows that in In nodejs, path is a module that is used frequently, but that people love and hate. Because some documents are not clear enough, and some are because of platform differences in interfaces. This article will give you a detailed introduction to the path processing module path in Node.js. I hope it will be helpful to you in learning or using the module path. Let’s take a look.

Preface

In node.js, a path block is provided. In this module, many usages are provided, which can The methods and attributes used to process and convert paths are not so confusing if you classify the interfaces of paths according to their uses and think about them carefully. Below we will introduce in detail the path processing module path in Node.js.

Get path/file name/extension

Get path: path.dirname(filepath)<br>

Get the file name: path.basename(filepath)<br>

Get the extension: path.extname(filepath)<br>

Get the path

The example is as follows:

var path = require(&#39;path&#39;);
var filepath = &#39;/tmp/demo/js/test.js&#39;;

// 输出:/tmp/demo/js
console.log( path.dirname(filepath) );

Get the file name

Strictly speaking, path.basename(filepath) is just the output path The last part 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(&#39;path&#39;);

// 输出:test.js
console.log( path.basename(&#39;/tmp/demo/js/test.js&#39;) );

// 输出:test
console.log( path.basename(&#39;/tmp/demo/js/test/&#39;) );

// 输出:test
console.log( path.basename(&#39;/tmp/demo/js/test&#39;) );

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

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

Get the file extension

A simple example is as follows:

var path = require(&#39;path&#39;);
var filepath = &#39;/tmp/demo/js/test.js&#39;;

// 输出:.js
console.log( path.extname(filepath) );

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

From The last one of B. Start intercepting until the last character.

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

Look directly at the official documentation for examples

path.extname(&#39;index.html&#39;)
// returns &#39;.html&#39;

path.extname(&#39;index.coffee.md&#39;)
// returns &#39;.md&#39;

path.extname(&#39;index.&#39;)
// returns &#39;.&#39;

path.extname(&#39;index&#39;)
// returns &#39;&#39;

path.extname(&#39;.index&#39;)
// returns &#39;&#39;

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(&#39;path&#39;);

// 输出 &#39;/foo/bar/baz/asdf&#39;
path.join(&#39;/foo&#39;, &#39;bar&#39;, &#39;baz/asdf&#39;, &#39;quux&#39;, &#39;..&#39;);

The pseudo code defined by path is as follows:

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

path.resolve([...paths])

The description of this interface is a bit verbose. 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 examplepath.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(&#39;path&#39;);

// 假设当前工作路径是 /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(&#39;&#39;) )

// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path
console.log( path.resolve(&#39;.&#39;) )

// 输出 /foo/bar/baz
console.log( path.resolve(&#39;/foo/bar&#39;, &#39;./baz&#39;) );

// 输出 /foo/bar/baz
console.log( path.resolve(&#39;/foo/bar&#39;, &#39;./baz/&#39;) );

// 输出 /tmp/file
console.log( path.resolve(&#39;/foo/bar&#39;, &#39;/tmp/file/&#39;) );

// 输出 /Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path/www/js/mod.js
console.log( path.resolve(&#39;www&#39;, &#39;js/upload&#39;, &#39;../mod.js&#39;) );

##Path analysis

path.parse(path)

path.normalize(filepath)

From Judging 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 /.


I feel like a brother on stackoverflow has a more realistic explanation of this API, here is the original link.

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(&#39;path&#39;);
var filepath = &#39;/tmp/demo/js/test.js&#39;;

var index = 0;

var compare = function(desc, callback){
 console.log(&#39;[用例%d]:%s&#39;, ++index, desc);
 callback();
 console.log(&#39;\n&#39;);
};

compare(&#39;路径为空&#39;, function(){
 // 输出 .
 console.log( path.normalize(&#39;&#39;) );
});

compare(&#39;路径结尾是否带/&#39;, function(){
 // 输出 /tmp/demo/js/upload
 console.log( path.normalize(&#39;/tmp/demo/js/upload&#39;) );

 // /tmp/demo/js/upload/
 console.log( path.normalize(&#39;/tmp/demo/js/upload/&#39;) );
});

compare(&#39;重复的/&#39;, function(){
 // 输出 /tmp/demo/js
 console.log( path.normalize(&#39;/tmp/demo//js&#39;) );
});

compare(&#39;路径带..&#39;, function(){
 // 输出 /tmp/demo/js
 console.log( path.normalize(&#39;/tmp/demo/js/upload/..&#39;) );
});

compare(&#39;相对路径&#39;, function(){
 // 输出 demo/js/upload/
 console.log( path.normalize(&#39;./demo/js/upload/&#39;) );

 // 输出 demo/js/upload/
 console.log( path.normalize(&#39;demo/js/upload/&#39;) );
});

compare(&#39;不常用边界&#39;, function(){
 // 输出 ..
 console.log( path.normalize(&#39;./..&#39;) );

 // 输出 ..
 console.log( path.normalize(&#39;..&#39;) );

 // 输出 ../
 console.log( path.normalize(&#39;../&#39;) );

 // 输出 /
 console.log( path.normalize(&#39;/../&#39;) );
 
 // 输出 /
 console.log( path.normalize(&#39;/..&#39;) );
});

File path decomposition/composition

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

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 of all, 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)

然后是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)

阅读相关API文档说明后发现,path.format(pathObject)中,pathObject的配置属性是可以进一步精简的。

根据接口的描述来看,以下两者是等价的。

     root vs dir:两者可以互相替换,区别在于,路径拼接时,root后不会自动加/,而dir会。

     base vs name+ext:两者可以互相替换。

var path = require(&#39;path&#39;);

var p1 = path.format({
 root: &#39;/tmp/&#39;, 
 base: &#39;hello.js&#39;
});
console.log( p1 ); // 输出 /tmp/hello.js

var p2 = path.format({
 dir: &#39;/tmp&#39;, 
 name: &#39;hello&#39;,
 ext: &#39;.js&#39;
});
console.log( p2 ); // 输出 /tmp/hello.js

path.parse(filepath)

path.format(pathObject) 的反向操作,直接上官网例子。

四个属性,对于使用者是挺便利的,不过path.format(pathObject) 中也是四个配置属性,就有点容易搞混。

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

获取相对路径

接口:path.relative(from, to)

描述:从from路径,到to路径的相对路径。

边界:

     如果from、to指向同个路径,那么,返回空字符串。

     如果from、to中任一者为空,那么,返回当前工作路径。

上例子:

var path = require(&#39;path&#39;);

var p1 = path.relative(&#39;/data/orandea/test/aaa&#39;, &#39;/data/orandea/impl/bbb&#39;);
console.log(p1); // 输出 "../../impl/bbb"

var p2 = path.relative(&#39;/data/demo&#39;, &#39;/data/demo&#39;);
console.log(p2); // 输出 ""

var p3 = path.relative(&#39;/data/demo&#39;, &#39;&#39;);
console.log(p3); // 输出 "../../Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.11.08-node-path"

平台相关接口/属性

以下属性、接口,都跟平台的具体实现相关。也就是说,同样的属性、接口,在不同平台上的表现不同。

    path.posix:path相关属性、接口的linux实现。

    path.win32:path相关属性、接口的win32实现。

    path.sep:路径分隔符。在linux上是/,在windows上是``。

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

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

直接来例子更直观。

> path.win32.join(&#39;/tmp&#39;, &#39;fuck&#39;)
&#39;\\tmp\\fuck&#39;
> path.win32.sep
&#39;\\&#39;
> path.win32.join(&#39;\tmp&#39;, &#39;demo&#39;)
&#39;\\tmp\\demo&#39;
> path.win32.join(&#39;/tmp&#39;, &#39;demo&#39;)
&#39;\\tmp\\demo&#39;

path.delimiter

linux系统例子:

console.log(process.env.PATH)
// &#39;/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin&#39;

process.env.PATH.split(path.delimiter)
// returns [&#39;/usr/bin&#39;, &#39;/bin&#39;, &#39;/usr/sbin&#39;, &#39;/sbin&#39;, &#39;/usr/local/bin&#39;]

windows系统例子:

console.log(process.env.PATH)
// &#39;C:\Windows\system32;C:\Windows;C:\Program Files\node\&#39;

process.env.PATH.split(path.delimiter)
// returns [&#39;C:\\Windows\\system32&#39;, &#39;C:\\Windows&#39;, &#39;C:\\Program Files\\node\\&#39;]

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Vuex管理登录的状态解析

关于vue解决跨域路由冲突问题的思路

The above is the detailed content of Introduction to path processing module path in Node.js. For more information, please follow other related articles on the PHP Chinese website!

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools