• Node.js Video Tutorials

Node.js - path.extname() 方法



Node.js 的 path.extname() 方法屬於 path 模組,它根據路徑中最後一個句點 (.) 字元的出現位置返回檔案的副檔名部分。如果路徑的最後一部分沒有 (.),或者除了路徑 basename 的第一個字元之外沒有其他 (.) 字元,則返回空 字串

語法

以下是 path 模組中 Node.js path.extname() 方法的語法:

path.extname( path )

引數

  • path − 此引數包含用於提取該特定副檔名部分的檔案路徑。此方法需要此引數,並且必須將其指定為有效的 字串值。如果 path 不是字串,則會丟擲 TypeError

返回值

此方法返回一個 字串,該字串指定指定檔案路徑的副檔名部分。

示例

此方法將根據最後一個句點 (.) 字元的出現位置獲取 path 的副檔名部分,忽略路徑中的第一部分。

以下是 Node.js path.extname() 方法的不同變體。

const path = require('path');

var path1 = path.extname('main.js');
console.log(path1);

var path2 = path.extname('main.test.js');
console.log(path2);

var path2 = path.extname('main.');
console.log(path2);

var path2 = path.extname('.main');
console.log(path2);

var path2 = path.extname('main');
console.log(path2);

var path2 = path.extname('main..js');
console.log(path2);

var path2 = path.extname('main.js.');
console.log(path2);

輸出

執行上述程式後,將生成以下輸出:

.js
.js
.


.js
.

示例

如果我們將非 字串型別的值傳遞給 path 引數,則 path.dirname() 方法將丟擲 TypeError

在以下示例中,我們將 整數而不是 字串傳遞給方法的 path 引數。

const path = require('path');

var path1 = path.extname(86598798);
console.log(path1);

TypeError

如果我們編譯並執行上述程式,該方法將丟擲 TypeError,因為 path 引數不是 字串值。

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)
nodejs_path_module.htm
廣告