What's the difference between process.cwd() vs __dirname?

后端 未结 4 655
谎友^
谎友^ 2020-11-29 14:54

What\'s the difference between

console.log(process.cwd())

and

console.log(__dirname);

I\'ve seen both use

4条回答
  •  囚心锁ツ
    2020-11-29 15:49

    As per node js doc process.cwd()

    cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

    As per node js doc __dirname

    The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

    Let me explain with example,

    suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

    or simply with following folder structure

    Project 
    ├── main.js
    └──lib
       └── script.js
    

    main.js

    console.log(process.cwd())
    // C:\Project
    console.log(__dirname)
    // C:\Project
    console.log(__dirname===process.cwd())
    // true
    

    suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

    main.js

    require('./lib/script.js')
    console.log(process.cwd())
    // C:\Project
    console.log(__dirname)
    // C:\Project
    console.log(__dirname===process.cwd())
    // true
    

    script.js

    console.log(process.cwd())
    // C:\Project
    console.log(__dirname)
    // C:\Project\lib
    console.log(__dirname===process.cwd())
    // false
    

提交回复
热议问题