Node.js中的路径模块简介

Many people forget about one of Node’s most useful built-in modules, the path module. It’s a module with methods that help you deal with file and directory path names on the machine’s filesystem. In this article, we’re going to look at five of the tools path provides.

许多人忘记了Node最有用的内置模块之一,即path模块。 它是一个模块,其方法可以帮助您处理计算机文件系统上的文件和目录路径名。 在本文中,我们将研究path提供的五个工具。

Before we can start using the path module, we have to require it:

在我们开始使用path模块之前,我们必须要求它:

const path = require('path');

Something of note: path works a little bit differently depending on your OS, but that’s beyond the scope of this article. To read more about the differences in the way path works on POSIX systems and Windows, see the path documentation.

注意事项:根据您的操作系统, path工作方式略有不同,但这超出了本文的范围。 要了解有关路径在POSIX系统和Windows上工作方式的差异的更多信息,请参阅路径文档

Now that that’s out of the way, let’s look at all the things we can use path for.

既然这已经不成问题了,那么让我们看一下我们可以使用path所有东西。

path.join (path.join)

One of the most commonly used path methods is path.join. The join method takes two or more parts of a file path and joins them into one string that can be used anywhere that requires a file path. For this example, let’s say that we need the file path of an image, and we have the name of the image. For simplicity’s sake, we’ll assume it’s a png.

最常用的path方法之一是path.joinjoin方法采用文件路径的两个或多个部分,并将它们连接为一个字符串,该字符串可在需要文件路径的任何地方使用。 对于此示例,假设我们需要图像的文件路径,并且我们具有图像的名称。 为了简单起见,我们假定它是png。

const path = require('path');

let imageName = 'bob_smith';

let filepath = path.join(__dirname, '/images/useravatars/', imageName, '.png');
// We'll talk about what __dirname does a little later on.

console.log('the file path of the image is', filepath);
// the filepath of the image is
// C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png
// (actual output shortened for readability)

path.join documentation

path.join文档

path.basename (path.basename)

According to the path docs, the path.basename method will give you the trailing part of a path. In layman’s terms, it returns either the name of the file or directory that the file path refers to. For this example, let’s say we want to know the name of an image, but we were passed the whole file path.

根据path文档, path.basename方法将为您提供路径的结尾部分。 用外行术语来说,它返回文件名或文件路径引用的目录。 对于此示例,假设我们想知道图像的名称,但是我们传递了整个文件路径。

const path = require('path');

// Shortened for readability
let filepath = 'C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png';

let imageName = path.basename(filepath); 

console.log('name of image:', imageName);
// name of image: bob_smith.png

Now this is cool and all, but what if we want it without the extension? Lucky for us, we just have to tell path.basename to remove it.

现在这一切都很酷,但是如果我们不想要扩展名怎么办? 对我们来说幸运的是,我们只需要告诉path.basename将其删除即可。

const path = require('path');

// Shortened for readability
let filepath = 'C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png';

let imageName = path.basename(filepath, '.png');

console.log('name of image:', imageName);
// name of image: bob_smith

path.basename documentation

path.basename文档

路径名 (path.dirname)

Sometimes we need to know the directory that a file is in, but the file path we have leads to a file within that directory. The path.dirname function is here for us. path.dirname returns the lowest level directory in a file path.

有时我们需要知道文件所在的目录,但是我们拥有的文件路径会导致该目录中的文件。 path.dirname函数在这里供我们使用。 path.dirname返回文件路径中的最低级别目录。

const path = require('path');

// Shortened for readability
let filepath = 'C:/Users/.../Pictures/Photos/India2019/DSC_0002.jpg';

let directoryOfFile = path.dirname(filepath);

console.log('The parent directory of the file is', directoryOfFile);
// The parent directory of the file is C:/Users/moose/Pictures/Photos/India2019

path.dirname documentation

path.dirname文档

path.extname (path.extname)

Say we need to know what the extension of a file is. For our example we’re going to make a function that tells us if a file is an image. For simplicity’s sake, we’ll only be checking against the most common image types. We use path.extname to get the extension of a file.

假设我们需要知道文件的扩展名是什么。 对于我们的示例,我们将创建一个函数来告诉我们文件是否为图像。 为了简单起见,我们将仅检查最常见的图像类型。 我们使用path.extname来获取文件的扩展名。

const path = require('path');

let imageTypes = ['.png', '.jpg', '.jpeg'];

function isImage(filepath) {
  let filetype = path.extname(filepath);

  if(imageTypes.includes(filetype)) {
    return true;
  } else {
    return false;
  }
}

isImage('picture.png'); // true
isImage('myProgram.exe'); // false
isImage('pictures/selfie.jpeg'); // true

path.extname documentation

path.extname文档

路径归一化 (path.normalize)

Many file systems allow the use of shortcuts and references to make navigation easier, such as .. and ., meaning up one directory and current direction respectively. These are great for quick navigation and testing, but it’s a good idea to have our paths a little more readable. With path.normalize, we can convert a path containing these shortcuts to the actual path it represents. path.normalize can handle even the most convoluted paths, as our example shows.

许多文件系统允许使用的快捷键和引用,使导航更容易,如... ,分别表示一个目录和当前方向。 这些对于快速导航和测试非常有用,但是最好使我们的路径更具可读性。 使用path.normalize ,我们可以将包含这些快捷方式的路径转换为它代表的实际路径。 如我们的示例所示, path.normalize甚至可以处理最复杂的路径。

const path = require('path');

path.normalize('/hello/world/lets/go/deeper/./wait/this/is/too/deep/lets/go/back/some/../../../../../../../../..');
// returns: /hello/world/lets/go/deeper

path.normalize documentation

path.normalize文档

🎉 We’re done! That’s all we’re going to cover in this article. Keep in mind that there’s way more to path than what’s covered here, so I encourage you to check out the official path documentation. Hopefully you learned something, and thanks for reading!

🎉我们完成了! 这就是我们将在本文中介绍的全部内容。 请记住,除了此处介绍的内容外,还有更多的路径可以使用,因此,我鼓励您查看官方路径文档 。 希望您学到了一些东西,并感谢您的阅读!

翻译自: https://www.digitalocean.com/community/tutorials/nodejs-intro-to-path-module

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值