452

How can I get the file name from an absolute path in Nodejs?

e.g. "foo.txt" from "/var/www/foo.txt"

I know it works with a string operation, like fullpath.replace(/.+\//, ''), but I want to know is there an explicit way, like file.getName() in Java?

Jost
  • 199
  • 1
  • 3
  • 16
fxp
  • 6,792
  • 5
  • 34
  • 45

9 Answers9

806

Use the basename method of the path module:

path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'

Here is the documentation the above example is taken from.

Victor Stanciu
  • 12,037
  • 3
  • 26
  • 34
73

To get the file name portion of the file name, the basename method is used:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);

console.log(file); // 'python.exe'

If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);

console.log(file); // 'python'
greuze
  • 4,250
  • 5
  • 43
  • 62
Rubin bhandari
  • 1,873
  • 15
  • 20
  • 5
    If you want the file name without the extension, I recommend use: `path.parse(fileName).name` – hong4rc Oct 29 '20 at 05:47
42
var path = require("path");

var filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";

var name = path.parse(filepath).name;
console.log(name); //python

var base = path.parse(filepath).base;
console.log(base); //python.exe

var ext = path.parse(filepath).ext;
console.log(ext); //.exe
Kevin Muchwat
  • 1,445
  • 18
  • 18
16

For those interested in removing extension from filename, you can use https://nodejs.org/api/path.html#path_path_basename_path_ext

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
Tigertron
  • 628
  • 6
  • 6
  • 2
    Also [this comment](https://stackoverflow.com/questions/19811541/nodejs-get-file-name-from-absolute-path/19811573#comment74745217_19811573) is useful – diralik Sep 07 '18 at 20:15
4

If you already know that the path separator is / (i.e. you are writing for a specific platform/environment), as implied by the example in your question, you could keep it simple and split the string by separator:

'/foo/bar/baz/asdf/quux.html'.split('/').pop()

That would be faster (and cleaner imo) than replacing by regular expression.

Again: Only do this if you're writing for a specific environment, otherwise use the path module, as paths are surprisingly complex. Windows, for instance, supports / in many cases but not for e.g. the \\?\? style prefixes used for shared network folders and the like. On Windows the above method is doomed to fail, sooner or later.

leo
  • 8,106
  • 7
  • 48
  • 80
4

path is a nodeJS module meaning you don't have to install any package for using its properties.

import path from 'path'
const dir_name = path.basename('/Users/Project_naptha/demo_path.js')
console.log(dir_name)

// returns
demo_path.js
pryansh
  • 197
  • 1
  • 8
0

In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform. Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.

Visv M
  • 431
  • 4
  • 13
0

So Nodejs comes with the default global variable called '__fileName' that holds the current file being executed My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic

Below, I make use of the fileName string and then split it based on the path.sep. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.

You can write a service like this (Note this is in typescript , but you can very well write it in js )

export class AppLoggingConstants {

    constructor(){

    }
      // Here make sure the fileName param is actually '__fileName'
    getDefaultMedata(fileName: string, methodName: string) {
        const appName = APP_NAME;
        const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
        //const actualFileName = fileName;
     return appName+ ' -- '+actualFileName;
    }


}

export const AppLoggingConstantsInstance = new AppLoggingConstants();
vijayakumarpsg587
  • 1,079
  • 3
  • 22
  • 39
0

In Node.js, you can get the file name from an absolute path using the path module. Specifically, you can use the path.basename() function to extract the file name from a given path.

sample code:

const path = require('path');

const absolutePath = '/var/www/foo.txt';
const fileName = path.basename(absolutePath);

console.log(fileName); // Output: foo.txt

The path.basename() function will automatically extract the file name from the given path

alekstim
  • 91
  • 1
  • 5