Thursday, June 13, 2024

Node.js path.basename() Method With Examples

Path module in Node.js provides many utility methods to work with file and directory paths. In this article we'll see how to use path.basename() method which returns the last portion of a path that means you can extract the filename from the full path using this method.

Syntax of path.basename()

path.basename(path, suffix)
  • path- This is the file path from which last portion has to be extracted. This is a required parameter.
  • suffix- This is an optional parameter. If the filename ends with the given suffix (extension) then the extension is removed.

This method returns a string which is the extracted filename from the given path. A TypeError is thrown if path is not a string or if suffix is given and is not a string.

The default operation of the path.basename() method varies based on the operating system on which a Node.js application is running. Which means method will take care of both paths '/' (Posix) and '\' (Windows).

path.basename() example in Node.js

basename.js

const path = require('path'); 
console.log('filePath- ', __filename);
const fileName = path.basename(__filename); 
console.log(fileName);

Output

filePath-  D:\NETJS\ NodeJS\nodews\pathdemos\basename.js
basename.js

Here __filename variable is used to get the absolute path of the currently executing file. From that filename is extracted using path.basename() method.

path.basename() with suffix argument

If you pass file extension as the second argument then the extension is removed from the file name.

const path = require('path'); 

console.log('filePath- ', __filename);
console.log('File Extension- ', path.extname(__filename))

const fileName = path.basename(__filename, path.extname(__filename)); 
console.log(fileName);

Output

filePath-  D:\NETJS\NodeJS\nodews\pathdemos\basename.js
File Extension-  .js
basename

Note that path.extname() method is used here to get the extension of the file rather than hardcoding the file extension.

If you have Unix style file paths then also path.basename() method works without any problem.

const path = require('path'); 
const filePath = '/home/netjstech/nodejs/pathdemos/basename.js'
const fileName = path.basename(filePath); 
console.log(fileName);

Output

basename.js

That's all for this topic Node.js path.basename() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Node.js path.join() Method
  2. Node.js path.resolve() Method
  3. Writing a File in Node.js
  4. NodeJS Blocking Non-blocking Code
  5. Appending a File in Node.js

You may also like-

  1. Node.js REPL
  2. Creating HTTP server in Node.js
  3. Setting Wild Card Route in Angular
  4. Custom Pipe in Angular With Example
  5. Java trim(), strip() - Removing Spaces From String
  6. Java Phaser With Examples
  7. Difference Between Abstract Class And Interface in Java

No comments:

Post a Comment