I'm doing a basic operation where I start from a given directory, and I traverse up the filesystem until I hit the root. On Linux/Mac, the root is obviously /
and on Windows it can be C:\
or another drive letter of course. My question is whether or not there is a way for Node.js to identify what the root directory of the filesystem is.
Currently, I'm resorting to simply checking the last directory against path.normalize(dir + "/../")
to see if it stops changing. Is there a process
property/method out there? Maybe a module?
To check the path in asynchronous mode in the fs module we can use fs. stat() method. The fs. stat() method takes two parameters, first parameter is the path and the second is the callback function with two parameters, one is for error in case error occurred and the second parameter is the data retrieved by calling fs.
It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.
Another one, using path.parse
.
const path = require('path')
const getRootDir = () => path.parse(process.cwd()).root
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With