Node.js 中的路径模块介绍

许多人忘记了Node最有用的内置模块之一,路径模块,它是一个有方法的模块,可以帮助您处理机器的文件系统上的文件和目录路径名称。

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

1const path = require('path');

<$>[注] 注意点:‘path’ 根据您的操作系统工作略有不同,但这超出了本文的范围。

现在,这已经不行了,让我们看看我们可以使用路径的所有东西。

走路 加入

最常用的path方法之一是path.joinjoin方法需要一个文件路径的两个或多个部分,并将它们合并成一个字符串,可以在任何需要文件路径的地方使用。

 1const path = require('path');
 2
 3let imageName = 'bob_smith';
 4
 5let filepath = path.join(__dirname, '/images/useravatars/', imageName, '.png');
 6// We'll talk about what __dirname does a little later on.
 7
 8console.log('the file path of the image is', filepath);
 9// the filepath of the image is
10// C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png
11// (actual output shortened for readability)

path.join documentation

名称: 基地

根据路径文件,path.basename方法会给你路径的后续部分. 在俗语中,它会返回文件路径所指的文件或目录的名称。

1const path = require('path');
2
3// Shortened for readability
4let filepath = 'C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png';
5
6let imageName = path.basename(filepath); 
7
8console.log('name of image:', imageName);
9// name of image: bob_smith.png

现在这很酷,但如果我们想要它没有扩展呢?幸运的是,我们只需要说‘path.basename’来删除它。

1const path = require('path');
2
3// Shortened for readability
4let filepath = 'C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png';
5
6let imageName = path.basename(filepath, '.png');
7
8console.log('name of image:', imageName);
9// name of image: bob_smith

path.basename documentation

路名 路名

有时我们需要知道文件所在的目录,但我们所拥有的文件路径会导致该目录中的文件。

1const path = require('path');
2
3// Shortened for readability
4let filepath = 'C:/Users/.../Pictures/Photos/India2019/DSC_0002.jpg';
5
6let directoryOfFile = path.dirname(filepath);
7
8console.log('The parent directory of the file is', directoryOfFile);
9// The parent directory of the file is C:/Users/moose/Pictures/Photos/India2019

path.dirname documentation

外名 外名

假设我们需要知道文件的扩展是什么. 对于我们的例子,我们将创建一个函数,告诉我们文件是否是一个图像. 为了简单,我们只会检查最常见的图像类型。

 1const path = require('path');
 2
 3let imageTypes = ['.png', '.jpg', '.jpeg'];
 4
 5function isImage(filepath) {
 6  let filetype = path.extname(filepath);
 7
 8  if(imageTypes.includes(filetype)) {
 9    return true;
10  } else {
11    return false;
12  }
13}
14
15isImage('picture.png'); // true
16isImage('myProgram.exe'); // false
17isImage('pictures/selfie.jpeg'); // true

path.extname documentation

正常化 正常化

许多文件系统允许使用捷径和引用来简化导航,如............,分别意味着一个目录和当前方向。这些都非常适合快速导航和测试,但最好让我们的路径更易读。

1const path = require('path');
2
3path.normalize('/hello/world/lets/go/deeper/./wait/this/is/too/deep/lets/go/back/some/../../../../../../../../..');
4// returns: /hello/world/lets/go/deeper

路径.正常化文档

🎉我们完成了!这就是我们将在这篇文章中涵盖的全部。请记住,比这里所涵盖的还有更多的路径,所以我鼓励您查看官方的路径文件(https://nodejs.org/api/path.html)。

Published At
Categories with 技术
Tagged with
comments powered by Disqus