0

I am trying to create a command line application in Node.js

I have the following folder structure (which might be incorrect)

enter image description here

Now my users will install this globally using npm install -g so this can be used in any project.

Inside my code (index.js) I have the following line:

fs.readFile('./helpers/tailwind.css', (err,css)=>{
    
})

Problem is that when my users run this it cannot find the file since it attempts to find that file in the directory where the user is using the command line application.

So how can I read from the command line applications folders/files?

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364
  • [__dirname](https://nodejs.org/dist/latest-v14.x/docs/api/modules.html#modules_dirname) might help...something like `path.join(__dirname, './helpers/tailwind.css')` – David784 Sep 04 '21 at 14:46

1 Answers1

1

Loading files (aka using require or import) from a globally installed package is not possible according to the docs - (as well as per this answer) so your users would need to install your package on a per repo basis.

With that being said, you may be able to accomplish this via OS env vars, but then you run into different issues. Like how do you handle setting those env vars for users on Windows vs users on *nix?

In your package.json file you can add a "bin" prop so that anyone who installs your package can access those files by doing "./node_modules/bin/helpers". See here for more info

If you do not care about going the "bin" route (or if it doesn't apply) then you could always have your users do something like "./node_modules/<your_package_name>/<some_dir>/<some.file>" (replace necessary names in path).. You may be able to get away with something like "<your_package_name>/<some_dir>/<some.file>" as well, but again, this cannot be with a global package.

Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41