Created
September 20, 2010 19:27
-
-
Save deanh/588499 to your computer and use it in GitHub Desktop.
This file contains 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 http = require('http'); | |
var hitCnt = 0; | |
http.createServer(function (req, res) { | |
// myHitCnt is function scope, but the function is | |
// a callback and only exists with each req | |
var myHitCnt = 0; | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
hitCnt++; myHitCnt++; | |
console.log('Server 1: ' + hitCnt + ' / my: ' + myHitCnt); | |
res.end('Server 1: ' + hitCnt + ' / my: ' + myHitCnt + '\n'); | |
}).listen(8124, "127.0.0.1"); | |
console.log('Server running at http://127.0.0.1:8124/'); | |
(function () { | |
// myVar is function scoped in an anon func this maintains | |
// a counter for this server via closure | |
var myHitCnt = 0; | |
http.createServer(function (req, res) { | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
hitCnt++; myHitCnt++; | |
console.log('Server 2: ' + hitCnt + ' / my: ' + myHitCnt); | |
res.end('Server 2: ' + hitCnt + ' / my: ' + myHitCnt + '\n'); | |
}).listen(8125, "127.0.0.1"); | |
console.log('Server running at http://127.0.0.1:8125/'); | |
})(); | |
/* | |
2 calls to :8124 and 3 to :8125 | |
dean@dean:~/Devel$ node node_try.js | |
Server running at http://127.0.0.1:8124/ | |
Server running at http://127.0.0.1:8125/ | |
Server 1: 1 / my: 1 | |
Server 1: 2 / my: 1 | |
Server 1: 3 / my: 1 | |
Server 1: 4 / my: 1 | |
Server 2: 5 / my: 1 | |
Server 2: 6 / my: 2 | |
Server 2: 7 / my: 3 | |
Server 2: 8 / my: 4 | |
Server 2: 9 / my: 5 | |
Server 2: 10 / my: 6 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment