节点文件路径

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 file

    dirname :获取文件的父文件夹

  • basename: get the filename part

    basename :获取文件名部分

  • extname: get the file extension

    extname :获取文件扩展名

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.

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

翻译自: https://flaviocopes.com/node-file-paths/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值