Get current working directory name instead of path in Node.js
I'm working on a cli app 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?
javascript node.js
add a comment |
I'm working on a cli app 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?
javascript node.js
add a comment |
I'm working on a cli app 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?
javascript node.js
I'm working on a cli app 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?
javascript node.js
javascript node.js
edited Nov 14 '18 at 19:14
lucascaro
asked Nov 14 '18 at 7:42
lucascarolucascaro
3,72611731
3,72611731
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
What you are looking for is 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.
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 forcwd
– lucascaro
Nov 14 '18 at 8:00
@lucascaro Edited, the above should work as intended
– Nelson Owalo
Nov 14 '18 at 8:10
add a comment |
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!.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295229%2fget-current-working-directory-name-instead-of-path-in-node-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
What you are looking for is 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.
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 forcwd
– lucascaro
Nov 14 '18 at 8:00
@lucascaro Edited, the above should work as intended
– Nelson Owalo
Nov 14 '18 at 8:10
add a comment |
What you are looking for is 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.
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 forcwd
– lucascaro
Nov 14 '18 at 8:00
@lucascaro Edited, the above should work as intended
– Nelson Owalo
Nov 14 '18 at 8:10
add a comment |
What you are looking for is 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.
What you are looking for is 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.
edited Nov 14 '18 at 8:10
answered Nov 14 '18 at 7:46
Nelson OwaloNelson Owalo
1,112926
1,112926
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 forcwd
– lucascaro
Nov 14 '18 at 8:00
@lucascaro Edited, the above should work as intended
– Nelson Owalo
Nov 14 '18 at 8:10
add a comment |
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 forcwd
– lucascaro
Nov 14 '18 at 8:00
@lucascaro Edited, the above should work as intended
– Nelson Owalo
Nov 14 '18 at 8:10
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
Nov 14 '18 at 8:00
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
Nov 14 '18 at 8:00
@lucascaro Edited, the above should work as intended
– Nelson Owalo
Nov 14 '18 at 8:10
@lucascaro Edited, the above should work as intended
– Nelson Owalo
Nov 14 '18 at 8:10
add a comment |
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!.
add a comment |
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!.
add a comment |
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!.
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!.
edited Nov 14 '18 at 19:34
answered Nov 14 '18 at 7:42
lucascarolucascaro
3,72611731
3,72611731
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295229%2fget-current-working-directory-name-instead-of-path-in-node-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown