Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nodejs教程12:path(路径)模块 #43

Open
chencl1986 opened this issue Mar 18, 2019 · 0 comments
Open

Nodejs教程12:path(路径)模块 #43

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

path(路径)

path模块主要用来对文件路径进行处理,比如提取路径、后缀,拼接路径等。

path的使用

接下来通过一些例子熟悉一下path的使用:

代码示例:/lesson12/path.js

const path = require('path')

const str = '/root/a/b/1.txt'

console.log(path.dirname(str))  // 获取文件目录:/root/a/b
console.log(path.basename(str)) // 获取文件名:1.txt
console.log(path.extname(str)) // 获取文件后缀:.txt
console.log(path.resolve(str, '../c', 'build', 'strict')) // 将路径解析为绝对路径:C:\root\a\b\c\build\strict
console.log(path.resolve(str, '../c', 'build', 'strict', '../..', 'assets')) // 将路径解析为绝对路径:C:\root\a\b\c\assets
console.log(path.resolve(__dirname, 'build')) // 将路径解析为绝对路径:C:\projects\nodejs-tutorial\lesson12\build

值得一提的是path.resolve方法,它可以接收任意个参数,然后根据每个路径参数之间的关系,将路径最终解析为一个绝对路径。

__dirname指的是当前模块所在的绝对路径名称,它的值会自动根据当前的绝对路径变化,等同于path.dirname(__filename)的结果。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant