you can use a command line prompt to do node
meta-commands
.help shows help menu
.clear wipes out variables
Hello World
//include http library into the program
//http object has the http library functionality
var http = require( 'http' );
//unlike php, you have to create the server
//listen to port 8124
http.createServer( function(req, res){
//set http response header
res.writeHead(200, { 'Content-Type': 'text/plain'});
res.write( 'Hello' );
res.end( ' World\n');
}).listen(8124, "127.0.0.1" );
//print a message to stdout
console.log( 'Server running at http://127.0,0.1:8124/');
http.createServer([requestListener])
Returns a new web server object.
requestListener is optional and added to request event
response functions
response.writeHead(statusCode, [reasonPhrase], [headers])
Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable reasonPhrase as the second argument.
response.write(chunk, [encoding])
write a chunk of string or buffer to response
response.end([data], [encoding])
This method signals to the server that all of the response headers and body has been sent
Listening to event
server.on('event', function(a, b, c) {
//do things
});
server is an instance of eventEmitter, eventEmitter has two methods
on and
emit.
emit emits an event,
on listens to the event
A variation of the example would be:
var http = require( "http" );
var server = http.createServer();
server.listen( 9000 );
server.on( 'request', function(req, res ){
res.writeHead( 200, { "Content-Type": "text/plain" });
res.write( "Hello World" );
res.end();
});
console.log( "localhost:9000 running" );