如何在 Node.js 中获取没有扩展名的文件名
要在 Node.js 中获取不带扩展名的文件的名称,请使用 path
模块中的 parse()
方法来获取表示路径的对象。 此对象的 name 属性将包含不带扩展名的文件名。
const path = require('path');
path.parse('index.html').name; // index
path.parse('package.json').name; // package
path.parse('image.png').name; // image
parse() 方法
parse()
方法返回一个对象,其属性表示给定路径的主要部分。 它返回的对象具有以下属性:
- dir – 路径的目录。
- root – 操作系统中最顶层的目录。
- base – 路径的最后一部分。
- ext – 文件的扩展名。
- name – 不带扩展名的文件名。
path.parse('C://Code/my-website/index.html');
/*
Returns:
{
root: 'C:/',
dir: 'C://Code/my-website',
base: 'index.html',
ext: '.html',
name: 'index'
}
*/
如果路径不是字符串,则 parse()
会抛出 TypeError
。
// ❌ TypeError: Received type of number instead of string
path.parse(123).name;
// ❌ TypeError: Received type of boolean instead of string
path.parse(false).name;
// ❌ TypeError: Received type of URL instead of string
path.parse(new URL('https://example.com/file.txt')).name;
// ✅ Received correct type of string
path.parse('index.html').name; // index
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。