What's the difference between path.resolve and path.join?

前端 未结 3 1230
無奈伤痛
無奈伤痛 2020-12-12 09:02

Is there some difference between the following invocations?

path.join(__dirname, \'app\')

vs.

path.resolve(__dirname, \'app         


        
3条回答
  •  生来不讨喜
    2020-12-12 09:46

    The default operations of file system path vary based on the operating system we need some thing that abstract it. The path module provides utilities or API for working with file and directory paths. you can include it in your project using

    const path = require('path');
    

    The path.join and path.resolve are two different methods of the path module.

    Both these methods accept a sequence of paths or path segments.

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

    The path.join() method joins all given path segments together using the platform specific separator as a delimiter, then normalizes the resulting path.

    In order to better understand and differentiate behaviours, let me explain it with different scenarios.

    1. If we don't supply any arguments to or empty string

    in my case, 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 of the node process
    

    and on running result is as below

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

    The inference from above experiment is tha path.resolve() method will output the absolute path where as the path.join() returns . representing the current working directory or relative path if nothing is provided

    2. Adding a /path as any of arguments.

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

    and the result is

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

    The inference we can found with this experiment is that 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.

    path.join() concatenates each argument with OS specific separators while path.resolve() will resolve each argument with root and produce output.

提交回复
热议问题