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?
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))