Richard
Richard

Reputation: 32899

How to generate a random number for each page?

I'm using node.js and express, and I'd like to generate a random five-figure number in app.js and return it to the client.

I'd like to do this on the server rather than the client, because I want to be certain that the number is different for every user who is currently connected.

Here's my current (broken) code from app.js:

// My first attempt - a function to generate a random number.
// But this returns the same number to every client. 
function genRandNum() {
    return Math.floor(Math.random() * 90000) + 10000;
}
// Routes
app.get('/', function(req, res){
  res.render('index', {
    title: 'Hello world',
    random_id: genRandNum() // No good - not different for each user. 
  });
});

There are actually two problems:

  1. How can I generate a number for each client?
  2. How can I be certain the number is different for every client? Do I need to create a Redis store of currently open sessions and their numbers?

Thanks for helping out a beginner :)

Upvotes: 6

Views: 4139

Answers (2)

Chandan
Chandan

Reputation: 229

For unique random numbers, you can also take the help from your user .. he can enter some random key strokes and then you can modify them/add/subtract something and send at server

Upvotes: 0

broofa
broofa

Reputation: 38102

Your code works for me, with index.jade:

h1 #{random_id}

However, as written it generates a random # for each page, not just each client. Some sort of backing data store would be needed to permanently guarantee each client has a unique #, but since you're only using 5-digits (90K possible IDs), you're clearly not concerned with this being unguessable. And if you only care about this in the context of a single node process, why not just use an auto incrementing value?

var clientId = 1;
app.get('/', function(req, res){
  res.render('index', {
    title: 'Hello world',
    random_id: clientId++ 
  });
});

Upvotes: 2

Related Questions