跳到内容

Node.js 文件路径

🌐 Node.js File Paths

系统中的每个文件都有一个路径。在 Linux 和 macOS 上,路径可能看起来像:/users/joe/file.txt,而 Windows 电脑则不同,其结构可能是:C:\users\joe\file.txt

🌐 Every file in the system has a path. On Linux and macOS, a path might look like: /users/joe/file.txt while Windows computers are different, and have a structure such as: C:\users\joe\file.txt

在应用中使用路径时需要注意,因为必须考虑到这种差异。

🌐 You need to pay attention when using paths in your applications, as this difference must be taken into account.

你可以使用 const path = require('node:path'); 将此模块包含到你的文件中,然后就可以开始使用它的方法了。

🌐 You include this module in your files using const path = require('node: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:获取文件的父文件夹
  • basename:获取文件名部分
  • extname:获取文件扩展名

示例

🌐 Example

const  = ('node:path');

const  = '/users/joe/notes.txt';

.(); // /users/joe
.(); // notes.txt
.(); // .txt

你可以通过为 basename 指定第二个参数来获取不带扩展名的文件名:

🌐 You can get the file name without the extension by specifying a second argument to basename:

path.basename(notes, path.extname(notes)); // notes

使用路径

🌐 Working with paths

你可以使用 path.join() 来连接路径的两个或多个部分:

🌐 You can join two or more parts of a path by using path.join():

const  = 'joe';
path.join('/', 'users', , 'notes.txt'); // '/users/joe/notes.txt'

你可以使用 path.resolve() 获取相对路径的绝对路径计算结果:

🌐 You can get the absolute path calculation of a relative path using path.resolve():

path.resolve('joe.txt'); // '/Users/joe/joe.txt' if run from my home folder

在这种情况下,Node.js 会简单地将 /joe.txt 附加到当前工作目录。如果你指定第二个参数 folder,resolve 将使用第一个参数作为第二个参数的基础:

🌐 In this case Node.js will simply append /joe.txt to the current working directory. If you specify a second parameter folder, resolve will use the first as a base for the second:

path.resolve('tmp', 'joe.txt'); // '/Users/joe/tmp/joe.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', 'joe.txt'); // '/etc/joe.txt'

path.normalize() 是另一个有用的函数,当路径中包含类似 ... 的相对标识符,或双斜杠时,它将尝试计算实际路径:

path.normalize('/users/joe/..//test.txt'); // '/users/test.txt'

resolve 和 normalize 都不会检查路径是否存在。它们只是根据已有的信息计算路径。