Open In App

How to Generate Random and Unique Password in Node.js using ‘generate-password’ NPM Module ?

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The “generate-password” module is a very useful and important external NPM module that can generate unique and random passwords for our projects. One of the main advantages of using this module is that it allows developers to easily generate passwords with various requirements, such as length, complexity, and character sets. This can save developers a lot of time and effort, as they don’t have to write their own password generation code from scratch. 

Installation of generate-password module: First, we have to install the module. You can install this by using the command given below. After this, this module gets added to your project in ‘package.json’ file. You can also check details about the modules in json file.

$ npm install generate-password

Folder structure:

folder structure

Use the module: To generate a password, we have to import ‘generate-password’ module using the require function and then call generate method by passing the length of the password, character set, etc. It will generate the password according to the values passed to the generate method. Below is the code to import the module into our application.

var generator = require('generate-password');

Run the code: After successfully importing the module and writing the code, We can run the code, using the following command in the terminal. Here index.js is the name of the file.

$ node index.js

Here are some examples of how can we use “generate-password” module:

Example 1:

Javascript




var generator = require('generate-password');
  
var passcode = generator.generate({
    length: 10,
    numbers: true
});
  
console.log(passcode);


Output:

example 1

Example 2:

Javascript




const generator = require('generate-password');
  
const password = generator.generate({
    length: 8,
    numbers: true,
    symbols: true,
    uppercase: false,
    excludeSimilarCharacters: true,
    strict: true,
  
});
  
console.log(password);


Output:

example 2

Conclusion: In conclusion, the “generate-password” NPM module provides developers with a valuable resource for generating secure passwords that meet specific criteria, such as length and character types. This module is user-friendly, highly configurable, and offers a range of options to create robust passwords. However, it’s important to note that while this tool can assist with password generation, it’s the user’s responsibility to implement proper password management and security practices.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads