path.join vs path.resolve with __dirname

前端 未结 3 1834
难免孤独
难免孤独 2020-12-04 08:11

Is there a difference when using both path.join and path.resolve with __dirname for resolving absolute path in Node.js?

3条回答
  •  無奈伤痛
    2020-12-04 08:25

    const absolutePath = path.join(__dirname, some, dir);
    

    vs.

    const absolutePath = path.resolve(__dirname, some, dir);
    

    path.join will concatenate __dirname which is the directory name of the current file concatenated with values of some and dir with platform specific separator.

    Where as

    path.resolve will process __dirname , some and dir i.e. from right to left prepending it by processing it.

    if any of the values of some or dir corresponds to a root path then the previous path will be omitted and process rest by considering it as root

    Inorder to better understand the concept let me explain both a little bit more detailed as follows :-

    The path.join and path.resolve are two different methods or functions of the path module provided by nodejs.

    Where both accept a list of path but the difference comes in the result i.e. how they process these path.

    path.join concatenates all given path segments together using the platform specific separator as a delimiter, then normalizes the resulting path. While the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

    When no arguments supplied

    Following example will help you to clearly understand both concepts:-

    My filename is index.js and the current working directory is E:\MyFolder\Pjtz\node

    const path = require('path');
    
    console.log("path.join() : ", path.join());
    // outputs .
    console.log("path.resolve() : ", path.resolve());
    // outputs current directory or equalent to __dirname
    

    Result

    λ node index.js
    path.join() :  .
    path.resolve() :  E:\MyFolder\Pjtz\node
    

    path.resolve() method will output the absolute path where as the path.join() returns . representing the current working directory if nothing is provided

    When some root path is passed as arguments

    const path=require('path');
    
    console.log("path.join() : " ,path.join('abc','/bcd'));
    console.log("path.resolve() : ",path.resolve('abc','/bcd'));
    

    Result i

    λ node index.js
    path.join() :  abc\bcd
    path.resolve() :  E:\bcd
    

    path.join() only concatenates the input list with platform specific separator while the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

提交回复
热议问题