HomeBlogWeb DevelopmentNode.js Path Module: Hands-on Guide with Examples

Node.js Path Module: Hands-on Guide with Examples

18th Sep, 2023
view count loader
Read it in
8 Mins
In this article
    Node.js Path Module: Hands-on Guide with Examples

    Node.js is an Open-Source and Cross-platform JavaScript runtime environment built on the V8 JavaScript engine – the core of google chrome. It is used to build highly performant and scalable applications and is an event-driven non-blocking I/O model.

    Working with File Paths

    Node.js is a Cross-platform which implies that an application developed in Node.js on OSX should be able to deploy it on Windows servers and Linux servers. Linux servers are similar to OSX as both are based on UNIX but Windows servers are a little different. For more information, check out Full Stack Development course.   

    Working with a file is one of the common most requirements like reading from a file, writing/updating to a file, etc. Some of the common file formats that are typically dealt with are importing or exporting data from/to JSON, Excel, CSV formats. To perform these operations, the Node.Js application has to deal with the filesystem of the Operating system in which the application is deployed. Node.js comes with an ‘fs’ module for dealing with files. But the most common issue to deal with supporting multiple operating systems is PATHS. As each operating system has its specific set of guidelines and if we dealt wrongly with them, then we are sure to run into problems.

    For example, backward slash (‘\’) on windows would be a directory separator whereas the same on a Unix-based system is an escape character and the forward-slash (‘/’) is used for directory separator on Unix-based system. Though Windows supports forward slash, Microsoft suggests using a backward slash.

    Another set of common requirements is dealing with newline characters. In a Unix-based system, ‘\n’ is used while some other platforms use \r and there are platforms like Windows which use both i.e., \n\r. And reading the file to support multiple platforms would mean that we have to come up with a complex regex or write conditional logic based on the platform at the expense of maintenance of the application.

    Writing to temp directory while performing some complex computation is a common requirement as well along with reading files from the home directory. Node.js comes with another module called ‘os’ which helps to build a more cross-platform application.

    Like End of Line (EOL) is obtained as require(‘os).EOL and require(‘os’).tmdir() to ensure the correct thing is done based on the platform.

    Introduction to PATH Module

    Node.js has a module called PATH to interact with file and directory paths. Node.js has a module called FS to interact with file and directory systems i.e., create, modify and delete while listing files. Both are meant for different purposes. FS assumes that the path provided is valid and performs the operations on the files. Unlike FS, the PATH module builds, parses an,d accesses papatth in the file system with the help of useful properties and methods.

    Below is a snippet of code for accessing path module:

    const path = require('path');

    Node.js path module behavior varies based on the operating system i.e., Windows or POSIX. This implies that if the node.js application is running in windows it will work as per Windows-style paths and the same thing applicable on POSIX. Throughout the article, we will be covering Windows and POSIX separately with respective examples.

    Path module has separate namespaces for windows and POSIX which helps in dealing the paths based on the corresponding platform.

    Working with Path.basename

    Path module has a basename method to get the file name part and usage of the same function in Windows and POSIX( I.e. Unix) differs.

    On POSIX -

    console.log(path.basename(' /temp/test.js'));   
    // returns test.js 
    console.log(path.basename(' /temp/test.js', ‘.js’));   
    // returns test – without the extension

    // Wrong format i.e., backward slash is used

    console.log(path.basename(' C:\\temp\\test.js'));   
    // returns C:\temp\test.js

    On WINDOWS -

    // returns test.js

    Node.js path can be used to get consistent results irrespective of Operating Systems with the help of specific implementation methods. To provide access to Windows-specific implementation of path methods, path.win32 to be used. It is accessible as require(‘path’).win32 or require(‘path/win32’).

    Working with WINDOWS file paths on POSIX platform -

    // returns 'test.js'

    Similar for POSIX files paths, path.posix to be used. It is accessible as require(‘path’).posix or require(‘path/posix’).

    Working with POSIX file paths on Windows platform -

    console.log(path.posix.basename(' /temp/test.js'));  
    // returns 'test'.js

    Here is a full example on Unix machine based on path provided:


    • Create an index.js file and copy the below code.
    const path = require('path');
    • Invoke a terminal and navigate to the directory of the index.js file location.
    • Execute node index.js to see the below output.


    /Users/.../.nvm/versions/node/v14.16.1/bin/node ./test.js
    test.js                                      test.js:3
    test.js                                      test.js:4
    test.js                                      test.js:5

    ON UNIX machine in POSIX path format:

    const path = require('path');
    console.log(path.basename('users/userName/desktop/test.js', '.js'));
    console.log(path.win32.basename('users/userName/desktop/test.js', '.js'));
    console.log(path.posix.basename('users/userName/desktop/test.js', '.js'));


    test                     test.js:3
    test                     test.js:4
    test                     test.js:5

    Path.basename takes an optional second argument which is the extension to get the file name without the extension.

    const path = require('path');
    console.log(path.basename('/temp/test.js', ‘.js’));
    console.log(path.win32.basename('C:\\temp\\test.js', ‘.js’));
    console.log(path.posix.basename('/temp/test.js', ‘.js’));

    Path.basename method takes second argument as file extension to remove file extension but basename methods treats extension as case-sensitive.a 

    Console.log(path. basename ('/temp/test.JS', '.js'));
    // returns 'test.JS'

    Note: If there is an invalid argument of different type other than string is sent then TypeError is thrown.

    The below set of examples can be executed by following below steps:

    • Open the terminal.
    • Run node to switch to REPL env.
    • Copy line by line to see the output mentioned.

    Working with Path.resolve

    Resolve method helps to resolve multiple path segments into an absolute path. Below are few examples.
    Joining paths:

    > path.resolve('/foo/bar', './baz') 
    > path.resolve('/foo/bar', '../baz') 
    > path.resolve('/foo/bar', '/baz') 

    Note: Per-drive working directory concept is followed by node.js on windows. For ex: path.resolve(‘c:\\’) might give different result to path.resolve(‘c:’). Reference

    > path.win32.resolve('c:\\') 
    > path.win32.resolve('c:') 

    There is a disparity in the path.delimiter based on the platform. In case of WINDOWS, it is semi-colon (;) and in POSIX is colon (:).
    Path segment separator also differs based on the platform. For Windows, path.sep is ‘\’ and for POSIX it is ‘/’.

    > path.win32.delimiter
    > path.posix.delimiter
    > path.win32.sep
    > path.posix.sep

    Working with Path.dirname

    Path.dirname is a helper method to get the parent directory for the given path.

    > path.dirname('desktop/test.js')

    Working with Path.extname

    Path.extname gives the extension of the path based on the last occurrence of the (.) period character ignoring the first character in the path. Below are the different variations of the method:

    > path.extname('test.js')
    > path.extname('sample.test.js')
    > path.extname('test.')
    > path.extname('.js')
    > path.extname('test')
    > path.extname('test..js')
    > path.extname('test.js.')

    Working with Path.format and path.parse

    Path.format and path.parse are just two sides of the coin which does opposite. Path.format takes an object and returns a path string whereas path.parse takes a path string and returns an object.
    Let’s understand the pathObject Object and its properties. It is a JavaScript object with the below properties:

    • dir              <string>
    • root            <string>
    • base          <string>
    • name         <string>
    • ext             <string>

    Each property has a specific priority and higher priority property overrides the lower one.

    • pathObject.dir has higher priority when compared to pathObject.root and if it is provided then pathObject.root is ignored.
    • path.base has higher priority when compared to pathObject.ext and pathObject.name. Path.base is considered over pathObject.ext and pathObject.name.

    Before proceeding further, you can enroll in Web Development courses list to advance in your career. Here is the path string returned for a given pathObject.




    Please follow the below steps to follow through.

    • Create an example.js file
    • Open the terminal and navigate to folder of example.js.
    • Copy code snippet from the example
      • Make sure to clear the content before proceeding with next one.
    • Run node example.js to view the expected output.

    Note: Below examples are verified in Unix machine but should be working in other OS as well.

    Sample example of path.format

    Let's understand with few examples

    const path = require('path');
                                dir: '/home/user/dir',
                                root: '/ignored',
                                base: 'file.txt'
    // returns ->  /home/user/dir/file.txt
                                dir: '/home/user/dir',
                                base: 'file.txt',
                                name: '/ignored',
                                ext: '/ignored'
    // returns ->  /home/user/dir/file.txt
                                dir: '/home/user/dir',
                                name: 'file',
                                ext: '.txt'
    // returns ->  /home/user/dir/file.txt
                                root: '/home/user/dir',
                                name: '/file',
                                ext: '.txt'
    // returns ->  /home/user/dir/file.txt

    On executing node index.js should return the expected output.

    As we have seen in the above examples, all of them return same result with different properties in pathObject. Let’s take the same output string and check the pathObject returned if we pass it to path.parse method.

    Sample example of path.parse

    On POSIX platform:

    const path = require('path');


    {root: '/', dir: '/home/user/dir',  base: 'file.txt',  ext: '.txt', name: 'file'}

    From the output it is evident that base is a combination of ext and name properties. And root is root path with rest of the directory path is set to dir property.

    • root: ‘/’,
    • dir: ‘/home/user/dir’,
    • base: ‘file.txt’,
    • ext: ‘.txt’,
    • name: ‘file’

    On Windows Platform:

    const path = require('path');


    {root: 'c:\\', dir: 'c:\\path\\dir', base: 'file.txt', ext: '.txt', name: 'file'}

    PathObject’s root property corresponds to the diver in windows and dir to the root directory of the file given. Base property is a combination of ext and name as in POSIX platform.

    • root: ‘c:\\’,
    • dir: ‘c:\\path\\dir’,
    • base: ‘file.txt’,
    • ext: ‘.txt’,
    • name: ‘file’

    Working with Path.normalize

    Path.normalize is another method helpful for normalizing the path by resolving ‘..’ and ‘.’ segments.

    const path = require('path');



    In the last example, normalize has replaced the multiple instances of path segment separates with single instance of path segment separator specific to the platform.

    Are you ready to unlock the power of Python? Join our Python course and become a coding wizard in no time! Don't miss out on this opportunity to learn one of the most versatile and in-demand programming languages. Enroll now and take your skills to the next level.

    Working with Path.join

    Path.join takes an array of path segments and joins them together using the platform-specific separator and performs normalization on the resulting path. This method is more reliable when compared to string concatenation because of extra caution to be taken for supporting multiple platforms.

    const path = require('path'); 
    console.log(path.join('/home', '/user', 'subdir', '/dir/', '/..'));



    Let’s decode how the output is obtained.  
    Step1 – all parameters are concatenated with a path separator in between each parameter based on platform-specific path segment separator.


    Step2 – Normalization is happened i.e., multiple instances of path segment separator are replaced with single instance.


    Sept 3 - And ‘..’ segments are resolved.


    Exploring the Path Further

    We’ve seen how we can use the path module and what we must be careful of and what differences we are likely to see in the functioning of the path module on different operating systems.

    There is a lot more to the Path module than what we have covered in this short article. The Path module is used with FS and OS module most of the time, and if you are interested in reading more about it, you should go through the official documentation too.https://nodejs.org/api/path.html.


    Sumanth Reddy


    Full stack,UI Architect having 14+ Years of experience in web, desktop and mobile application development with strong Javascript/.Net programming skills .Strong experience in microsoft tech stack and Certified in OCI associate. Go-to-guy on integration of applications, building a mobile app by zeroing on tech stack. Majorily experienced on engineering based IIOT products and Marekting Automation products deployed on premise and on-cloud. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon