Skip to content

Instantly share code, notes, and snippets.

@sferik
Created May 24, 2013 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sferik/5640537 to your computer and use it in GitHub Desktop.
Save sferik/5640537 to your computer and use it in GitHub Desktop.
var fortunes = [
"Have a nice day",
"You look really good today",
"It's your birthday!",
"Never play leapfrog with a unicorn"
];
var net = require('net');
var server = net.createServer(function(connection){
connection.write("Enter the number of fortunes you want: ");
connection.on('data', function(data){
var num_fortunes = parseInt(data, 10);
if(isNaN(num_fortunes)) {
connection.write("That's not a number, silly.")
connection.end();
} else if(num_fortunes > 4) {
connection.write("You're too greedy. Ask for fewer fortunes next time.");
connection.end();
} else {
for(var i = 0; i < num_fortunes; i += 1) {
connection.write(fortunes[i] + "\n");
}
connection.end();
}
connection.on('error', function(){});
})
});
server.listen(1234);
@agsdot
Copy link

agsdot commented May 24, 2013

for(var i = 0; i < num_fortunes; i += 1) {
var fortune = fortunes[Math.floor(Math.random() * fortunes.length)];
connection.write(fortune.toString() + "\n");

gives a random number output for the fortune

@agsdot
Copy link

agsdot commented May 24, 2013

if(isNaN(num_fortunes)) {
  connection.write("That's not a number, silly." + "\n");
  connection.end();
} else if(num_fortunes > 4) {
  connection.write("You're too greedy. Ask for fewer fortunes next time." + "\n");
  connection.end();
} else if(num_fortunes < 1) {
  connection.write("You need to ask for more than 0." + "\n");
  connection.end();

++

added one more condition, if the number is less than 1 and also added newline characters for the output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment