如何在 Node.js 中获取没有扩展名的文件名
作者:迹忆客
最近更新:2022/10/10
浏览次数:
要在 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
相关文章
如何在 Python 中从路径获取文件名
发布时间:2023/12/20 浏览次数:95 分类:Python
-
本教程将演示 Python 中如何从路径中获取文件名,不论是什么操作环境下。使用 ntpath 库从路径中获取文件名 定义路径的方式可以是不同的。
Node.js 中的 HTTP 发送 POST 请求
发布时间:2023/03/27 浏览次数:456 分类:Node.js
-
在本文中,我们将学习如何使用 Node.js 使用第三方包发出发送 post 请求。