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?

1
  • __dirname might help...something like path.join(__dirname, './helpers/tailwind.css') Commented Sep 4, 2021 at 14:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The above comment used the path.join would that not work from a global installed package?
The issue isn't the paths you are using. Rather where the package is located on the end users machine. Using path.join wouldn't change anything.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.