Search code examples
node.jspathfs

Get file name from absolute path in Nodejs?


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?


Solution

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