迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Node.js >

如何在 Node.js 中获取文件的扩展名

作者:迹忆客 最近更新:2022/10/11 浏览次数:

要在 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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 Python 中获取文件扩展名

发布时间:2023/12/24 浏览次数:88 分类:Python

它演示了如何在 Python 中获取文件扩展名。本教程将介绍如何在 Python 中从文件名中获取文件扩展名。

在 C++ 中获取文件扩展名

发布时间:2023/08/25 浏览次数:150 分类:C++

文件扩展名是指文件名的最后部分,其中包含有关文件中保存的数据的信息。在 C++ 中,我们可以对包含 C++ 代码的文件使用 .cpp 或 .cxx 扩展名。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便