path 模块的 Node.js path.extname() 方法将根据路径中最后一次出现的 (.) 句点字符为您提供特定文件路径的扩展部分。如果路径的最后一部分没有 (.) 字符,或者如果路径的基名的第一个字符之外没有 (.) 字符,则将返回一个空字符串。
语法
以下是路径模块的Node.js path.extname()方法的语法 -
参数
- path − 此参数包含用于提取该特定文件的扩展部分的文件路径。此方法需要此参数,并且必须指定为有效的字符串值。如果 path 不是字符串,则会抛出 TypeError。
返回值
此方法返回一个字符串,该字符串指定指定文件路径的扩展部分。
例此方法将根据最后一次出现的 (.) 句点字符获取路径的扩展部分,忽略路径中的第一部分。
以下是 Node.js path.extname() 方法的不同变体。
输出
在执行上述程序时,它将生成以下输出 -
.js
.js
.
.js
.
.js
.
.js
.
例
如果我们将一个不是字符串类型的值传递给 path 参数,path.dirname() 方法将抛出 TypeError。
在下面的示例中,我们将整数而不是字符串传递给方法的路径参数。
类型错误
如果我们编译并运行上述程序,该方法会抛出 TypeError,因为路径参数不是字符串值。
path.js:39
throw new ERR_INVALID_ARG_TYPE('path', 'string', path);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type number
at assertPath (path.js:39:11)
at Object.extname (path.js:1375:5)
at Object.<anonymous> (/home/cg/root/63a028ab0650d/main.js:3:18)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
throw new ERR_INVALID_ARG_TYPE('path', 'string', path);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type number
at assertPath (path.js:39:11)
at Object.extname (path.js:1375:5)
at Object.<anonymous> (/home/cg/root/63a028ab0650d/main.js:3:18)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)