Random Password Generator with Node.js

Watch out! This tutorial is over 7 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

Now that Node.js server is available as a template via Xen Orchestra it’s time to look at some of the cooler stuff you can do with Node.js. Here are instructions for how to build your own online Random Password Generator.

We’ll need a couple of npm packages to start with, so log into your new Node.js server and execute the following:

sudo npm install --save crypto-random-string
sudo npm install --save readline
sudo npm install --save http
sudo npm install --save ip

Now open a new file for editing, randompassword.js

nano randompassword.js

The contents will be similar to this:

// we'll need this to create our web page
var http = require('http'); 

// we'll also need this to get the current server IP address
var ip = require("ip");

//we'll need this to accept user input
var readline = require('readline');

//we'll need this to generate passwords
const cryptoRandomString = require('crypto-random-string');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("How many passwords do you require? ", function(answer) {

   // create our http server 
   http.createServer(function (req, res) 
   { 

     // sending a response header of 200 OK 
     res.writeHead(200, {'Content-Type': 'text/plain'}); 


     //output the the required number of passwords
     for(var i = 0; i < answer;i++){

        res.write(cryptoRandomString(16)+'\n'); 

     }

     res.write("\nRefresh with F5 for new set of passwords.");

     res.end();

   }).listen(8080); 

   console.log('Success! Passwords available at http://'+ip.address()+':8080');

   rl.close();

});

To run our new script, execute

nodejs randompassword.js

The output will be something like this:

How many passwords do you require? 20
Success! Passwords available at http://10.108.158.9:8080

and when you visit the URL mentioned, you will see

234f39950bf9749c
fa5f209f06d1661f
0e4caf38030d6348
398db40cea8c71c9
4f89932ccd943085
25ae75ee0fbbe050
088ccd1d56ff5fe8
5780d3f0dd82219c
76ec20f22d76dc91
ab3551c87af0a74a
164a40a5e7c5127d
7665fd032b4e1a57
d044e18ae0e6a00d
45327a0aa820240d
74c67c286433897d
df3e31aaf68a7a0f
eff4e44e658814ce
1df4673eaa483b6e
be87d67dce768786
a1a44b311cfa9b8b

Refresh with F5 for new set of passwords.