Search code examples
node.jspath

How to get specific file's directory name without full path in Node.js?


Node.js official docs provide this example:

path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf'

However, I actually want 'asdf' instead of full path '/foo/bar/baz/asdf'.

Despite some string manipulation, what is the best way, or is there any official API I can directly get that piece of string?


Solution

  • You can use path.basename() on the directory path returned by path.dirname() as shown below. This method returns the last part of the given path.

    const path = require('path');
    const dirPath = path.dirname('/foo/bar/baz/asdf/quux');
    console.log(path.basename(dirPath))