One source of confusion when installing node.js packages via npm might be that a lot of instructions recommend installing some packages with the -global or -g flag.
Simply put, installing globally means that we can access the package from any place in your computer’s file system (as long as the place for our global installs is part of our path). Local installs, in contrast, are specific to projects.
I would recommend that most installations be local.
The reason for this is that if you have multiple projects and install a lot of things globally, you could end up breaking some of the projects (if an incompatible version of a package is installed, or some necessary dependencies aren’t honoured, for example).
To demonstrate the difference between the two places, let’s install a stupid little package called cowsay, which creates ASCII art cows that talk or think.
First we will install it globally. (If you’re on a Langara computer, this part assumes that you have already changed the location of the npm global packages directory).
In terminal, type the following. Because this is a global install (and you’ve set a “reachable” new location) it does not matter what folder you are currently in.
npm install cowsay -g
Once you’ve done that, run the following commands. The first moves you to the root level of the filesystem. The second runs the cowsay binary from there.
cd / cowsay i am a cow
Here’s the result (also installed with cowsay, by the way, is cowthink.
In a minute, we’ll do a local installation but first let’s delete the global cowsay installation.
npm uninstall -g cowsay
Now try running the cowsay command:
In other words, having uninstalled the cowsay binary, the command no longer works.
Now make a folder on your desktop called npm-testing and install cowsay without the global flag.
cd ~/Desktop mkdir npm-testing cd npm-testing npm install cowsay
Once you’ve done that, make a directory listing (ls). You will see a node-modules folder and a package-lock.json file. If you run the cowsay command now, it still won’t work. Because it’s not globally installed, it will not work without the exact path specified.
Navigate into the node_modules directory, then into the cowsay directory.