Get file name from absolute path in Nodejs?

node.jsPathFs

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

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'

Solution 3 - node.js

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

Solution 4 - node.js

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

Solution 5 - node.js

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.

Solution 6 - node.js

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.

Solution 7 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfxpView Question on Stackoverflow
Solution 1 - node.jsVictor StanciuView Answer on Stackoverflow
Solution 2 - node.jsRubin bhandariView Answer on Stackoverflow
Solution 3 - node.jsKevin MuchwatView Answer on Stackoverflow
Solution 4 - node.jsTigertronView Answer on Stackoverflow
Solution 5 - node.jsleoView Answer on Stackoverflow
Solution 6 - node.jsVisv MView Answer on Stackoverflow
Solution 7 - node.jsvijayakumarpsg587View Answer on Stackoverflow