Last active
December 26, 2015 05:59
-
-
Save skeggse/7104135 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var net = require('net'); | |
var EventEmitter = require('events').EventEmitter; | |
// just define this in the file scope, you don't need to assign it as a property | |
var numApples = 50; | |
// pickers, because this can handle multiple pickers | |
var fruitPickers = new EventEmitter(); | |
// replentish apples every thirty seconds | |
setInterval(function() { | |
numApples++; | |
}, 30000); | |
// you don't instantiate the net module, you just call createServer | |
var server = net.createServer(function(fruitPicker) { | |
// this is more common, there's really no point in setting this as a property | |
var pickedApples = 0; | |
// the server doesn't emit data events, just the individual connection | |
fruitPickers.on('pickOne', function() { | |
fruitPicker.write('A fruitBat picked an apple. ' + numApples + ' left.'); | |
}) | |
fruitPicker.setEncoding('utf-8'); | |
fruitPicker.on('data', function(data) { | |
// always use triple-equals, it doesn't do weird and inefficient type conversions (0 === 0, but 0 !== '0') | |
if (data[0] === 'p') { | |
pickedApples++; | |
numApples--; | |
fruitPickers.emit('pickOne'); | |
} | |
}); | |
}); | |
var port = 3000 || process.env.PORT; | |
server.listen(port, function() { | |
console.log('listening on', port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment