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:获取文件的父文件夹

    ¥dirname: gets the parent folder of a file

  • basename:获取文件名部分

    ¥basename: gets the filename part

  • extname:获取文件扩展名

    ¥extname: gets the file extension

示例

¥Example

const path = require('node:path');

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

path.dirname(notes); // /users/joe
path.basename(notes); // notes.txt
path.extname(notes); // .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 name = 'joe';
path.join('/', 'users', name, '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 附加到当前工作目录。如果你指定第二个参数文件夹,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() is another useful function, that will try and calculate the actual path, when it contains relative specifiers like . or .., or double slashes:

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

解析和规范化都不会检查路径是否存在。它们只是根据获得的信息计算路径。

¥Neither resolve nor normalize will check if the path exists. They just calculate a path based on the information they got.