Skip to content

Instantly share code, notes, and snippets.

@torgeir
Created June 24, 2010 17:19
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 torgeir/451692 to your computer and use it in GitHub Desktop.
Save torgeir/451692 to your computer and use it in GitHub Desktop.
A simple "chat" application using Node.js
/*
Usage:
$ node chat.js
$ curl http://127.0.0.1:8124/say?one
// say!
$ curl http://127.0.0.1:8124/say?two
// say!
$ curl http://127.0.0.1:8124/ask
// ["one", "two"]
*/
// chat.js
var sys = require('sys'),
url = require('url'),
http = require('http');
var messages = [];
http.createServer(function (request, response) {
var req = url.parse(request.url);
if (req.pathname == '/say') {
messages.push(req.query);
sendResponse('say!', 200, response);
}
else if (req.pathname == '/ask') {
sendResponse(JSON.stringify(messages), 200, response);
}
else {
sendResponse('not found!', 404, response);
}
}).listen(8124);
function sendResponse(bodyText, httpCode, response){
response.writeHead(httpCode, {
'Content-Length': bodyText.length,
'Content-Type': 'text/plain'
});
response.end(bodyText);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment