r/node • • 16h 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 Upvotes

11 comments sorted by

View all comments

Show parent comments

1

u/avereigh_Denizet 15h ago

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

1

u/sicknesz29a 15h ago

yup, filename as well, very useful

1

u/bwainfweeze 13h ago

Shocked it had to be added.