r/node • • 22d 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?

5 Upvotes

15 comments sorted by

View all comments

7

u/sysrage 21d 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.

2

u/avereigh_Denizet 21d ago

Wait did `import.meta.dirname` finally make it into LTS? Somehow missed that.

2

u/sicknesz29a 21d ago

yup, filename as well, very useful

2

u/bwainfweeze 21d ago

Shocked it had to be added.

2

u/bwainfweeze 21d ago

My last project had a lot of small modules we started adding CLIs to a number of foundational modules for debugging and triage reasons. Things like reloadable config and feature toggle code sprouted the ability to check settings from outside the program.

In addition to __dirname, we also ensured the file structure had the same nesting depth in node_modules as in the source tree so that everything ran mostly the same regardless of whether you had a git repo cloned or the package installed.

In general it’s a bad idea to rearrange your project directory when packaging anyway. Makes for human errors, and as the project grows it adds noticeable overhead to build/test cycles. I’ve seen it approach half of build time across three programming languages.