Tristan
Tristan

Reputation: 9141

NodeJS package management

I wanted to run this simple line of code (using Node.js 8.0.0) :

time node -e "console.log(require('bcrypt').hashSync(process.argv[1], 8));" your-password-here

to compare bcrypt to bcryptjs on my RaspberryPi running Linux Alpine.

At first it gave me :

module.js:487
    throw err;
    ^    
Error: Cannot find module 'bcrypt'
    at Function.Module._resolveFilename (module.js:485:15)
    at (...)
    at evalScript (bootstrap_node.js:432:27)

So I tried to install bcrypt with this command :

npm install -g --production bcrypt

which worked (after a fallback to compile from sources since the linux depencies were not found for my armv7 processor).

BUT when trying the test command again, I had exactly the same error (cannot find module 'bcrypt').

It's only after doing what I think is a "project local" install without the "-g" option (even if I had no project) it finally worked and bcrypt was found when running my test command.

npm install bcrypt

Could some someone familiar with NodeJS explain me this strange mechanism ?

Upvotes: 1

Views: 211

Answers (1)

MySidesTheyAreGone
MySidesTheyAreGone

Reputation: 129

Globally installed packages are not automatically available everywhere. Installing one like you did is a great idea on a platform where clearly you want to compile as little as possible given how long it takes; however, you still need to link globally-installed packages in your local project:

# install globally
npm install -g --production bcrypt


# link locally (you must run this in your project's directory)
npm link bcrypt

This will create symlink(s) that will simply make the globally-installed module available in the node_modules directory of your local project - a much faster operation than recompiling the module once for every project that requires it.

Make sure, however, to remember to update bcrypt running npm install -g --production bcrypt again when a new version you need is released. Running npm update in your project won't suffice.

npm link documentation, well worth a read. Note that the behavior of this command is completely different if run without a package name as its argument.

Upvotes: 2

Related Questions