Every file in the system has a path.
系统中的每个文件都有一个路径。
On Linux and macOS, a path might look like:
在Linux和macOS上,路径可能类似于:
/users/flavio/file.txt
/users/flavio/file.txt
while Windows computers are different, and have a structure such as:
Windows计算机有所不同,并且具有以下结构:
C:\users\flavio\file.txt
C:\users\flavio\file.txt
You need to pay attention when using paths in your applications, as this difference must be taken into account.
在应用程序中使用路径时,您需要注意,因为必须考虑到这种差异。
You include this module in your files using
您使用
const path = require('path')
and you can start using its methods.
您可以开始使用其方法。
从路径中获取信息 (Getting information out of a path)
Given a path, you can extract information out of it using those methods:
给定路径,您可以使用以下方法从中提取信息:
dirname
: get the parent folder of a filedirname
:获取文件的父文件夹basename
: get the filename partbasename
:获取文件名部分extname
: get the file extensionextname
:获取文件扩展名
Example:
例:
const notes = '/users/flavio/notes.txt'
path.dirname(notes) // /users/flavio
path.basename(notes) // notes.txt
path.extname(notes) // .txt
You can get the file name without the extension by specifying a second argument to basename
:
您可以通过为basename
指定第二个参数来获得不带扩展名的文件名:
path.basename(notes, path.extname(notes)) //notes
使用路径 (Working with paths)
You can join two or more parts of a path by using path.join()
:
您可以使用path.join()
路径的两个或多个部分:
const name = 'flavio'
path.join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'
You can get the absolute path calculation of a relative path using path.resolve()
:
您可以使用path.resolve()
获得相对路径的绝对路径计算:
path.resolve('flavio.txt') //'/Users/flavio/flavio.txt' if run from my home folder
In this case Node will append /flavio.txt
to the current working directory. If you specify a second parameter folder, resolve
will use the first as a base for the second:
在这种情况下,Node将/flavio.txt
附加到当前工作目录。 如果指定第二个参数文件夹,则resolve
将使用第一个作为第二个的基础:
path.resolve('tmp', 'flavio.txt')//'/Users/flavio/tmp/flavio.txt' if run from my home folder
If the first parameter starts with a slash, that means it’s an absolute path:
如果第一个参数以斜杠开头,则表示它是绝对路径:
path.resolve('/etc', 'flavio.txt')//'/etc/flavio.txt'
path.normalize()
is another useful function, that will try and calculate the actual path, when it contains relative specifiers like .
or ..
, or double slashes:
path.normalize()
是另一个有用的函数,当它包含类似的指定符时,它将尝试计算实际路径.
或..
或双斜杠:
path.normalize('/users/flavio/..//test.txt') ///users/test.txt
Both resolve and normalize will not check if the path exists. They just calculate a path based on the information they got.
解析和规范化都不会检查路径是否存在 。 他们只是根据获得的信息来计算路径。