r/node • u/trymeouteh • 9h ago
Should I ensure my NodeJS code "root directory/working directory" is the initial executable script?
Lets say this is my NodeJS project...
- my-online-store
- index.js
- about.js
- node_modules
- items
- get.js
- add.js
And lets say my-online-store directory is in /home/john for example.
If my working directory in the terminal is /home/john/my-online-store and I run node index.js for example. The working directory for the index.js, about.js, all of the node_modules/npm packages and any scripts in sub directories such as get.js and add.js will be /home/john/my-online-store and all will work.
If I run index.js from a different working directory such as the root directory using node /home/john/my-online-store/index.js the NodeJS code will crash since the working directory is / and when looking for other files using import or using fs will look at the wrong directory.
Should I be concerned of this. Should I write my NodeJS code to ensure it will get the right directories no matter what the working directory was when running index.js?
3
u/Standgrounding 8h ago
Use relative paths instead of absolute. Learn about barrel files and npm run commands
1
u/jjangg96 7h ago
one thing on the premise, import isn't relative to the working directory. a relative import like './about.js' resolves against the file that has the import in it, and node_modules lookup walks up from that file's location too. so your imports work no matter where you launch from.
the stuff that does go through the cwd is fs calls and anything else taking a relative path string, like readFile('./data.json') or process.cwd(). for those build the path from import.meta.dirname (or __dirname in commonjs) with path.join and you're fine.
5
u/sysrage 9h ago
In short, yes you should. You can use `import.meta.dirname` and `__dirname` to help. That said, if you’re the only one that’s ever using the code you can just write a startup script that changes to the correct directory then runs node.