Node.js: module not found after installing it with npm -g

Viewed 1026

I have installed the tar-module using

npm install -g tar

When I type

npm list -g --depth=0

I can see the entry tar@6.1.0 in the module-tree, however when I try to require it in a js-file const tar = require("tar"), I get the error message

Uncaught Exception:
Error: Cannot find module 'tar'

What am I missing?

1 Answers

The issue here is that you're trying to use something installed globally in a local project. You should be able to use your libraries if you install them inside the project with npm i tar.

The reason we install something globally is for use during development on many projects. This way, we don't have to install a tool on every project. With something you want to use inside a projects code however, you should install it on a project level. This way everything that the project needs to work lives inside of the project itself. You should see all dependencies listed inside of your package.json file

Not gonna advocate you do this, but if you really want to include the globally installed library, you can do something like this:

require('./../../.npm-global/lib/node_modules/tar'); // Relative path to library

Where you go up the file directory to your $HOME directory into the default global install location for node and bring it in. This is poor practice, please don't do it, but heres the info none-the-less.

Related