Full steps to create a password generator using Node.js

Full steps to create a password generator using Node.js

1. Preparation

1.1 Create a project

$ npm init 

1.2 Installation Dependencies

$ npm i commander chalk clipboardy

1.3 Create the entry file index.js

Let's take a look at process.argv

// index.js
console.log(process.argv)

Terminal execution command

$ node index

In the terminal you can see

The process.argv property returns an array containing the command line arguments passed in when the Node.js process was started. The first element will be process.execPath. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.

Execute Command

$ node index generate

The third parameter: generate

2. Writing command lines

2.1 Add version and description

// index.js
const program = require('commander');
program.version('1.0.0').description('Simple password generator').parse()

Terminal execution command: You can see the description of passgen

Continue to execute the command: you can see the version of passgen

2.2 Configure password length command

const program = require('commander');

program.version('1.0.0').description('Simple password generator')
program.option('-l --length <number>', 'length of password').parse()
console.log(program.opts())

Terminal execution command: you can see the password length command of passgen

Terminal execution command:

2.2 Added default value for password length: 8

program.option('-l --length <number>', 'length of password', '8').parse()
console.log(program.opts())

Terminal execution command: Do not set the password length, you can see that the default value -8 is used

Terminal execution command: Set the password length to 10

2.3 Configuring the save password command

program.option('-l --length <number>', 'length of password', '8')
.option('-s --save', 'save password to password.txt').parse()

2.4 Configure password format: No numbers

.option('-nn --no-number', 'remove numbers').parse()

Terminal execution command: By default, there are numbers

Terminal execution command: Set and clear digital password

2.5 Configuration password format: No symbols

.option('-ns --no-symbols', 'remove symbols').parse()

Terminal execution command: By default, it has symbols

Terminal execution command: Set and clear digital password

3. Parsing the command line - creating a password

// index.js
const program = require('commander');
const createPassword = require('./utils/createPassword')
const log = console.log

program.version('1.0.0').description('Simple password generator')
program
.option('-l --length <number>', 'length of password', '8')
.option('-s --save', 'save password to password.txt')
.option('-nn --no-numbers', 'remove numbers')
.option('-ns --no-symbols', 'remove symbols').parse()

const {length, save, numbers, symbols} = program.opts()

// Get generated password
const generatedPassword = createPassword(length, numbers, symbols)

// Output generated password

log(generatedPassword)

Create utils/createPassword.js

// createPassword.js
const alpha = 'qwertyuiopasdfghjklzxcvbnm'
const numbers = '0123456789'
const symbols = '!@#$%^&*_-=+'


const createPassword = (length = 8, hasNumbers = true, hasSymbols = true) => {
    let chars = alpha
    hasNumbers ? (chars += numbers): ''
    hasSymbols ? (chars += symbols): ''
    return generatePassword(length, chars)
}

const generatePassword = (length, chars) => {
    let password = ''
    for(let i = 0; i < length; i++){
        password+= chars.charAt(Math.floor(Math.random()*chars.length))
    }
    return password
}
module.exports = createPassword

Terminal execution command: View password generation

3.1 Adding color

// index.js
const chalk = require('chalk');
log(chalk.blue('Generated Password: ') + chalk.bold(generatedPassword))

Terminal executes command: You can see the color changes

3.2 Add Clipboard

// index.js
const clipboardy = require('clipboardy');
// Copy to clipboardy
clipboardy.writeSync(generatedPassword)
log(chalk.yellow('Password copied to clipboardy!'))

4. Save the password to the corresponding file

// index.js
const savePassword = require('./utils/savePassword')
// Save to file
if (save) savePassword(generatedPassword)

Create utils/savePassword.js

const fs = require('fs')
const path = require('path')
const os = require('os')
const chalk = require('chalk')

const savePassword = (password) => {
    fs.open(path.join(__dirname, '../', 'passwords.txt'), 'a', '666', (e, id) => {
        fs.write(id, password + os.EOL, null, 'utf-8', ()=>{
            fs.close(id, ()=>{
                console.log(chalk.green('Password saved to passwords.txt'))
            })
        })
    })
}

module.exports = savePassword

Execute the command in the terminal: You can see that the passwords.txt file is generated in the project and the password has been saved successfully

5. Configure local npm modules as global passgen

// package.json
  "preferGlobal": true,
  "bin":"./index.js",

Terminal execution command:

npm link command: link the npm module to the corresponding running project to facilitate debugging and testing of local modules

//index.js
#!/usr/bin/env node //Add the first line

Terminal execution command:

Summary: It’s done ✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️

Reference link: nodejs.cn/api/process…

Summarize

This is the end of this article about using Node.js to create a password generator. For more information about Node.js password generator, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

<<:  MySQL replication mechanism principle explanation

>>:  How to install redis5.0.3 in docker

Recommend

Navicat cannot create function solution sharing

The first time I wrote a MySQL FUNCTION, I kept g...

How to use JS code compiler Monaco

Preface My needs are syntax highlighting, functio...

How to install and configure the Apache Web server

Learn how to host your own website on Apache, a r...

Why MySQL does not recommend using null columns with default values

The answer you often hear is that using a NULL va...

How to obtain and use time in Linux system

There are two types of Linux system time. (1) Cal...

Installation steps of docker-ce on Raspberry Pi 4b ubuntu19 server

The Raspberry Pi model is 4b, 1G RAM. The system ...

Detailed Example of JavaScript Array Methods

Table of contents Introduction Creating an Array ...

How to implement simple data monitoring with JS

Table of contents Overview first step Step 2 Why ...

The pitfalls of deploying Angular projects in Nginx

Searching online for methods to deploy Angular pr...

Implementation of css transform page turning animation record

Page turning problem scenario B and C are on the ...

Dynamic starry sky background implemented with CSS3

Result:Implementation Code html <link href=...

A brief discussion on MySQL B-tree index and index optimization summary

MySQL's MyISAM and InnoDB engines both use B+...