How To Fix The Error “Cannot Find Module ‘bcrypt'” In Node.js

Cannot find module 'bcrypt' in Node.js

We will share with you the cause of the error “Cannot find module ‘bcrypt'” in Node.js and how we can fix it. Let’s see what we can do in this whole article.

What does this error mean?

While working on a Node.js project, you receive the error message “Cannot find module ‘bcrypt'” because you have not installed the modules bcrypt and node-gyp. We need to install both modules node-gyp because module bcrypt uses it for installation and building purposes.

As a result, when you try to import modules bcrypt into a file, an error occurs:

const bcrypt = require('bcrypt');
//..other lines of code

Error:

Solution for the error “Cannot find module ‘bcrypt'” in Node.js 

To solve this problem, open the terminal on the root directory. Then run the commands below to install the required packages for your project:

However, sometimes the above command will not help you to install module ‘bcrypt’. Then you will have to install it in the following way:

npm install -g bcrypt
npm link bcrypt

After installation, open the file ‘package.json’ in your project. Your installation is considered successful only if the installed modules must be nested in object ‘dependencies‘. Otherwise, your installation has failed. Check if the console window shows any error after you run the install command. For example, your ‘package.json‘ should be like this:

{
  "dependencies": {
    "bcrypt": "^5.1.0",
    // ... other options
  }
}

In case the error is still not fixed, you can try to remove the folder ‘node_modules’ and file ‘package-lock.json‘, then open the terminal and run the ‘npm install‘ command:

rm -rf node_modules
rm -f package-lock.json
npm install

We recommend you restart the IDE and development server after running all the commands for the system to catch up with the latest updates.

At this point, everything seems to be smooth, and the error no longer occurs. Here is a sample program using module ‘bcrypt’.

const bcrypt = require('bcrypt');
 
async function hashPassword(plaintextPassword) {
    const hash = await bcrypt.hash(plaintextPassword, 10);
    console.log('result: ' + hash)
}
 
hashPassword('We are LearnShareIT')

Note: You may get different results when you try to run the above program. The output above is just a specific case.

Output:

result: $2b$10$yU8/.BHxEO5ewDmDiTGSreiLabifU8/1nTi5qo.zQKJjCO751MVA6

Summary

Finally, we have gone through all the information about the error “Cannot find module ‘bcrypt'” in Node.js. Hopefully, the solutions we provide in this article work for you. Thank you for being so interested.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *