I'm developing a package for logging in Node.js. I want to able to read the path of the project where my package is being used. That's because I want the user to be able to put a config file in the root of their project. I want to achieve something similar as the ESLint package being able to read the .eslintrc file.
I want to able to read the path of the project where my package is being used
process.argv[1] will be the fully qualified path of the root script that was executed (perhaps without file extension).
So, you can take that fully qualified path and then get just the directory like this:
const rootdir = path.dirname(process.argv[1]);
As you asked, this is the directory where the root script that started the whole nodejs program is located. That may or may not be where your particular module was loaded from. Your module could be loaded from some other module which was itself loaded from the root script.
Also, this is not necessarily the same directory as the current working directory, process.cwd(). If a path is passed to the root script, then the current working directory can literally be anything so it cannot be counted on to point at any specific module.
Note that good modularity will NOT have dependencies on specific parent modules or specific parent modules being located in certain places. If your module needs to know where some resources are located, it should be able to find them in one of several ways:
__dirname or import.meta).You should generally not write a module that must have certain parent modules in known locations. Somewhat by definition, that's not an easily shareable, reusable module if it can only be used by a specific other module that has a specific structure.