Get current working directory name instead of path in Node.js












1















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?










share|improve this question





























    1















    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?










    share|improve this question



























      1












      1








      1








      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?










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 19:14







      lucascaro

















      asked Nov 14 '18 at 7:42









      lucascarolucascaro

      3,72611731




      3,72611731
























          2 Answers
          2






          active

          oldest

          votes


















          0














          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.







          share|improve this answer


























          • 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



















          0














          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!.






          share|improve this answer

























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


            }
            });














            draft saved

            draft discarded


















            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









            0














            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.







            share|improve this answer


























            • 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
















            0














            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.







            share|improve this answer


























            • 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














            0












            0








            0







            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.







            share|improve this answer















            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.








            share|improve this answer














            share|improve this answer



            share|improve this answer








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



















            • 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

















            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













            0














            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!.






            share|improve this answer






























              0














              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!.






              share|improve this answer




























                0












                0








                0







                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!.






                share|improve this answer















                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!.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 14 '18 at 19:34

























                answered Nov 14 '18 at 7:42









                lucascarolucascaro

                3,72611731




                3,72611731






























                    draft saved

                    draft discarded




















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Lugert, Oklahoma