How to get the file name from a path in Node.js?

December 2, 2020 - 1 min read

To get the file name or the last portion from a path, you can use the basename() method from the path module in Node.js.

Let's say we have a pathname called /app/controllers/index.js like this,

// pathname
const pathname = "/app/controllers/index.js";

We can get the filename from the above path by passing the pathname as an argument to the path.basename() method like this,

// require path module
const path = require("path");

// path name
const pathname = "/app/controllers/index.js";

// pass the pathname as an argument
// to path.basename() method
// to get the filename or last portion from the path
const filename = path.basename(pathname);

console.log(filename); // index.js
  • The path.basename() method returns the file name.

See this example live in repl.it.

Feel free to share if you found this useful 😃.