cft

Build a Node.Js password generator

So, without much do, let's get to dive in with this. Am gonna divide its development into clearly defined steps to avoid confusion


user

Jaskeerat Singh

3 years ago | 6 min read

A lot of times while filling forms online we all have come across registration forms that don't allow Google or any other social authentication and prompt the user to add a password to create an account successfully. For that also Google Chrome has a feature of Suggest strong password, but sometimes when you are too dependent on something, then it starts showing its disadvantages.

Most users save most of their passwords in their Google Account due to which the Suggest strong password stops coming. To solve that problem in that case I came up with this password generator CLI application built using Node.js which helps you generate a strong password based on your conditions like :

  • Length of password
  • Composition of password ( whether it should be numeric or alphabetic only or a mix of both or with symbols )

So, without much do, let's get to dive in with this. Am gonna divide its development into clearly defined steps to avoid confusion

Note :

Some pre-requisites to consider. Although it's a beginner-friendly project but make sure you have a working knowledge of Node.Js and Git.

  • Initialise an empty git repository if you want the code to be accessible online easily

Simply clone/download the repo into your local machine. Let's initialize the project :

  • npm init -y: The command helps to initialize your Node.Js project
  • npm install commander chalk clipboardly: These 3 Node.Js packages we will be using to make the CLI application. If you want to know about them, head over to projectDocs.txt in the "starterFiles" branch

OR

If you want to directly access the starter files, then simply download/clone them from github.com/Jassi10000/CustomPassword/tree/s..

  • Make a new file that will contain the application code. I named the file "password.js".

COPY

const program = require('commander');
program.version('1.0.0').description("Custom Password Generator");

// Let's now generate the commands we'll use in cli to generate passwords
program.command("get").action(() => {
console.log("Password generated");
}).parse();

Here, program is a global object exported by the commander, we define the version to be used and the description We define an action on a command that we gonna use to generate the password. I used "get" . Run the snippet of code with this command

COPY

node password.js get

It simply logs "Password generated"

  • Let's now generate some help commands for our CLI application users

COPY

const program = require('commander');
program.version('1.0.0').description("Custom Password Generator")

// let's see make how to make custom help commads
// <number> is used to generate the password of that specified length
program.option('-l, --length <number>' ,'length of password').parse()
console.log(program.opts());
// The parsed options can be accessed by calling .opts() on a Command object

We can even pass the desired length in the code itself by passing the length as the third argument to avoid writing in CLI

We can even check that if our command got included in the help commands list by

COPY

node password.js -h

Let's do some more help commands : We'll also check they are included in help commands or not

  • Let's destructure them and move towards the function that will help us generate passwords

But we'll prefer to make this createPassword function in a new folder utilities

  • Let's now code the createPassword function in "createPassword.js"

COPY

// define the numbers , symbols and alphabets
const numbers = '0123456789';
const symbols = '!@#$%^&*_+=';
const alphabets = 'abcdefghijklmnopqrstuvwxyz';

const createPassword = ( length = 12 , hasNumbers = true , hasSymbols = true) => {
// initially generates the password with all alphabet characters
let characters = alphabets;

// in case we want a combo of numbers and alphabets
hasNumbers ? (characters += numbers ) : ''
hasSymbols ? (characters += symbols ) : ''

return generatedPassword(length,characters);
};


const generatedPassword = (length,characters) => {
// initially the password is empty
let password = '';
for( let i = 0 ; i < length ; i++ ){
password += characters.charAt(Math.floor(Math.random() * characters.length));
}
return password;
}

module.exports = createPassword;

Let's see what we get when we run the code snippet in "password.js"

Yay!! we got a randomly generated password

Now, it will more interesting to play with commands. Let's try out random stuff

Let's now make our CLI look more beautiful by adding colors to it using chalk and use clipboardy to copy the password to the clipboard

COPY

const program = require('commander');
const chalk = require('chalk');
const clipboardy = require("clipboardy");
const createPassword = require("./utilities/createPassword");
program.version('1.0.0').description("Custom Password Generator")

// let's see make how to make custom help commads
// <number> is used to generate the password of that specified length
program
.option('-l, --length <number>' ,'length of password' , '12')
.option('-s, --save' ,'save the passwords to mypasswords.txt')
.option('-nn, --no-numbers' , 'generate password without number')
.option('-ns, --no-symbols' , 'generate password without symbol')
.parse()

// console.log(program.opts());
// The parsed options can be accessed by calling .opts() on a Command object --> which is program in our code

// let's destructure these all help commands
const { length , save , numbers , symbols } = program.opts();

const generatePassword = createPassword( length , numbers , symbols);

// copying password to clipboard
clipboardy.writeSync(generatePassword);

// making CLI colourful
console.log(chalk.yellow("Generated Password : " ) + chalk.green.bold(generatePassword));
console.log(chalk.red.bold("Password copied to clipboard !! "));

So, the last step is to save the generated passwords to a file. I will save it to "mypasswords.txt" and for that we will write a savePassword function in "savePassword.js in utilities folder.

COPY

const fs = require("fs");
const path = require("path");
const os = require("os");
const chalk = require("chalk");

const savePassword = (password) => {
// with fs.open it will find out mypasswords.txt if it exists otherwise it will simply create it
// 'a' here refers to append , means each password will be appended one after the other in the file
// 666 refers to the permissions
fs.open(path.join(__dirname , "../" , 'mypasswords.txt'), 'a', 666, (e , id) => {
fs.write(id , password + os.EOL , null , 'utf-8' , () => {
fs.close(id , () => {
console.log(chalk.cyan.bold("Password saved to mypasswords.txt"));
})
})
})
}


module.exports = savePassword;

We also have to make this accessible globally so we gonna make some changes in package.json and define the bin with the file that has the application code. In my case its password.js

Let's run our script to see what it does

The code runs nicely and also saves our password in "mypasswords.txt"

  • Note : We have to add the symlink to avoid doing " node password.js " again and again...

We have to generate a command which directly runs the script and generates password for us

Am gonna tell for various Operating System :

1. Unix O.S / Mac O.S / Linux :

COPY

#!/usr/bin/env node

Add this command to the starting of your JavaScript file to make it executable by the locally installed node program. This command is known as "shebang character sequence".

Make the JavaScript command-line file executable

COPY

chmod +x password.js           # Make the file executable

2. Windows O.S :

In Windows, that line will just be ignored because it will be interpreted as a comment, but it has to be there because npm will read it on a Windows machine when the NodeJS command-line package is being installed.

COPY

#!/usr/bin/env node

Add this command to the starting of your JavaScript file to make it executable by the locally installed node program.

For both the O.S choices we have to add this to our package.json

Now, this means that now getPass will be the command which will run my script instead of "node password.js"

The command name is customizable, you can write your name or any other name

Now , Link your command for development

For this, this command will help us

COPY

npm link

Once executed, we will see our command being symlinked globally.

Let's see how this works :

The password also got saved

Yayy !!!! it works

The full code is also available here 🤩

  • password.js
  • createPassword.js
  • savePassword.js

The full code is also uploaded on : Source Code

If this project helped in any way maybe its learning something new or doing hands of an already known skill , do like and share it to the world !!!! 🤩

Upvote


user
Created by

Jaskeerat Singh

I am a java coder and a MERN Stack Developer , always love to explore various tech around


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles