16

I'm working on a CLI application that needs to use the name of the current directory.

I can get the path to the current directory with process.cwd(). How can I get the current directory name instead of the whole path?

Is it OK to do something like the following?

process.cwd().split('/').slice(-1)[0]

It works, but it feels brittle. What is the best and most robust way of doing this?

2 Answers 2

25

Even though the code in the answer works, you should use path.basename() to get the name of the last portion of a path because:

  • It works across operating systems (windows and unix-like systems use different path separators)
  • It ignores trailing directory separators (i.e. the last / in /path/to/cwd/)

Additionally, and for extra safety, you should use path.resolve() because it normalizes the path before getting the base name, getting rid of path-related quirks.

If you can get the /path/to/cwd with process.cwd(), then the following will give you the name of the directory ("cwd" in the example):

path.basename(process.cwd())

Add path.resolve() for extra safety:

path.basename(path.resolve(process.cwd()))

or even:

path.basename(path.resolve())

Example:

const path = require('path');

function slice(pathName) {
  const res = pathName.split(path.sep).slice(-1)[0];
  console.log('slicer  ', pathName, '=>', `'${res}'`);
}

function basename(pathName) {
  const res = path.basename(path.resolve(pathName));
  console.log('basename', pathName, '=>', `'${res}'`);
}

slice('/path/to/cwd'); // cwd
basename('/path/to/cwd'); // cwd

slice('/path/to/cwd/'); // ''
basename('/path/to/cwd/'); // cwd

// Other valid paths
slice('/path/to/cwd/..'); // '..'
basename('path/to/cwd/..'); // cwd

slice('.'); // '.'
basename('.'); // <current directory name>

process.cwd()

Returns: <string>

The process.cwd() method returns the current working directory of the Node.js process.

console.log(`Current directory: ${process.cwd()}`);

This is guaranteed to be the absolute path to the current working directory. Use this!

path.basename(path[, ext])

path <string>
ext <string> An optional file extension
Returns: <string>

The path.basename() method returns the last portion of a path, similar to the Unix basename command. Trailing directory separators are ignored, see path.sep.

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

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'

A TypeError is thrown if path is not a string or if ext is given and is not a string.

path.resolve([...paths])

...paths <string> A sequence of paths or path segments
Returns: <string>

The path.resolve() method resolves a sequence of paths or path segments into an absolute path.

The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo, /bar, baz, calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz.

If after processing all given path segments an absolute path has not yet been generated, the current working directory is used.

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

Zero-length path segments are ignored.

If no path segments are passed, path.resolve() will return the absolute path of the current working directory.

If you can use process.cwd() you don't need path.resolve() in other cases, use it!.

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

Comments

7

You are looking for path.basename:

const path = require('path'); 
path.basename(CWD)

The path.basename() method returns the last portion of a path. Trailing directory separators are ignored.

2 Comments

Thanks for the answer! Since I don't have a path to a file but to the current working directory, path.dirname would give me the parent directory, i.e. path.basename(path.dirname('path/to/cwd')) === 'to' but I'm looking for cwd
@lucascaro Edited, the above should work as intended

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.