如何在 Node.js 中获取文件的扩展名
要在 Node.js 中获取文件的扩展名,我们可以使用 path
模块中的 extname()
方法。
const path = require('path');
path.extname('style.css') // .css
path.extname('image.png') // .png
path.extname('prettier.config.js') // .js
extname() 方法
extname()
方法从最后一次出现 .
(句点)字符到路径最后部分的字符串末尾。
如果没有 .
在路径的最后一部分,或者如果路径以 .
它是唯一的。 路径中的字符,extname()
返回一个空字符串。
path.extname('index.'); // .
path.extname('index'); // '' (empty string)
path.extname('.index'); // '' (empty string)
path.extname('.index.html'); // .html
如果路径不是字符串,则 extname()
会抛出 TypeError
。
const path = require('path');
// ❌ TypeError: Received type number instead of string
path.extname(123);
// ❌ TypeError: Received type boolean instead of string
path.extname(false);
// ❌ TypeError: Received URL instance instead of string
path.extname(new URL('https://example.com/file.txt'));
// ✅ Received type of string
path.extname('package.json'); // .json
相关文章
使用 PowerShell 获取文件扩展名
发布时间:2024/02/06 浏览次数:146 分类:编程语言
-
本文将讨论几种使用 PowerShell 脚本获取文件扩展名的方法。本文还提供了多种技术和示例。
在 Python 中获取文件扩展名
发布时间:2023/12/24 浏览次数:88 分类:Python
-
它演示了如何在 Python 中获取文件扩展名。本教程将介绍如何在 Python 中从文件名中获取文件扩展名。
在 C++ 中获取文件扩展名
发布时间:2023/08/25 浏览次数:150 分类:C++
-
文件扩展名是指文件名的最后部分,其中包含有关文件中保存的数据的信息。在 C++ 中,我们可以对包含 C++ 代码的文件使用 .cpp 或 .cxx 扩展名。
Node.js 中的 HTTP 发送 POST 请求
发布时间:2023/03/27 浏览次数:456 分类:Node.js
-
在本文中,我们将学习如何使用 Node.js 使用第三方包发出发送 post 请求。