• Node.js Video Tutorials

Node.js - path.extname() Method



The Node.js path.extname() method of path module will gives you the extension portion of a particular file path based on the last occurrence of the (.) period character in the path. In case there is no (.) in the last portion of the path, or if there is no (.) characters other than the first character of the basename of the path, an empty string will be returned.

Syntax

Following is the syntax of the Node.js path.extname() method of path module −

path.extname( path )

Parameters

  • path − This parameter holds the file path that would be used to extract the extension portion of that particular file. This parameter is required by this method and must be specified as a valid string value. A TypeError is thrown if path is not a string.

Return value

This method returns a string which specifies the extension portion of the specified file path.

Example

This method will get the extension portion of the path based on the last occurrence of the (.) period character ignoring the first portion in the path.

Following are the different variations of the Node.js path.extname() method.

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);

Output

On executing the above program, it will generate the following output −

.js
.js
.


.js
.

Example

If we pass a value which is not a string type to the path parameter, the path.dirname() method will throw a TypeError.

In the following example, we are passing integer instead of string to the path parameter of the method.

const path = require('path');

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

TypeError

If we compile and run the above program, the method throws an TypeError as the path parameter is not a string value.

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
Advertisements