480

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?

12 Answers 12

846

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..

Sign up to request clarification or add additional context in comments.

1 Comment

If you also want to remove the extension: path.basename(fpath, path.extname(fpath))
76

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'

1 Comment

If you want the file name without the extension, I recommend use: path.parse(fileName).name
50
var path = require("path");

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

var name = path.parse(filepath).name;
console.log("name:", name); // Output: python

var base = path.parse(filepath).base;
console.log("base:", base); // Output: python.exe

var ext = path.parse(filepath).ext;
console.log("ext:", ext); // Output: .exe

var dir = path.parse(filepath).dir;
console.log("dir:", dir); // Output: C:\Python27\ArcGIS10.2

var root = path.parse(filepath).root;
console.log("root:", root); // Output: C:\

OR

const path = require("path");
const filepath = "C:\\Python27\\ArcGIS10.2\\python.exe";

const { name, base, ext, dir, root } = path.parse(filepath);

console.log(`Name: ${name}\nBase: ${base}\nExtension: ${ext}\nDirectory: ${dir}\nRoot: ${root}`);

1 Comment

you forget root and dir
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');

1 Comment

Also this comment is useful
6

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.

6 Comments

Windows have \ as folder separator
@OwnageIsMagic Yes, that's why I write “If you already know that the path separator is /”... :)
it's not clear what you meant with this statement. This produces platform dependent code that will silently fail on on other platforms
@OwnageIsMagic Yes, it does indeed. Always use the methods of the path module if you are not writing for a specific platform.
windows actually accepts both / and \ as folder seperators & you can even mix it up
|
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

Comments

1

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

Comments

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.

1 Comment

Please elaborate your answer.
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();

Comments

0

In Node.js, you can use the built-in path module to get this. You can just utilize the path.basename() method, it extracts the last portion of a path.

check the below how you can get the file name from an absolute path:

const path = require('path');

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

console.log(fileName); // Output will be "mytext.txt" in this case

The above code will extract the file name (mytext.txt) from the absolute path (/var/www/mytext.txt) using path.basename(). Thanks

Comments

0

To get the file name from the absolute path. Use this method provided by path

const path=require('path');

const file_path="var/www/foo.txt";

const fileName=path.basename(file_path);

console.log(fileName) ;

//foo.txt

Comments

-1

I know it works with a string operation......

well here are a few anyway.... for anyone to compare and reference.

String Operations

  • No Modules Required OS Independant one liners

The one i thought of

'/var/www/foo.txt'.match(/[^\\/]+$/)[0]

An Alternative already suggested by @Visv M

'/var/www/foo.txt'.split(/[\\/]/).pop()

Ops Given Example, made OS independant

'/var/www/foo.txt'.replace(/.+[\\/]/, '')

there are ways to redefine skinning a cat

String Objects and their Methods

Regular Expressions in Javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.