0

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?

3 Answers 3

2

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

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

Comments

1

Offical API or module will also do a string manipulation, it's pretty simple:

path.dirname('/foo/bar/baz/asdf/quux').split("/").pop(); // asdf

For all platforms:

path.dirname('/foo/bar/baz/asdf/quux').split(/\/|\\/).pop(); // asdf

1 Comment

I think it is better to use path.basename() as your solution won't catch platform specific differences in the presentation of file paths. For example, your code may fail on Windows as the path separator is `\` on this platform.
1

I believe this simple line of code should give you the desired result.

path.basename(path.dirname("/foo/bar/baz/asdf/quux"))

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.