如何在 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

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