Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Node server
var http = require('http');
// Creates new Server object
// and takes a callback as param.
// The callback is an event listener;
// When server emits particular event,
// this function will be called.
// Callback takes 2 parameters,
// request (type IncomingRequest)
// and response (type ServerResponse).
// Returns a Server object
http.createServer(function(req, res) {
// Here we build our response to a request
// ServerResponse.writeHead takes as parameters:
// 1. statusCode: number
// 2. reasonPhrase?: string
// 3. headers?: OutgoingHttpHeaders
// writeHead writes header of response
res.writeHead(200, {'Content-Type': 'text/plain'});
// end() method sends content of the response to the client
// and signals to the server that the response
// has been sent completely.
// If you are going to send anything else, use
// write() instead of end().
// end() must be called on each response.
// end() takes params:
// 1. data: string
// 2. encoding?: string
// 3. callback?: Function
// If callback is specified, it wil be called when
// the response stream is finished.
res.end('Hello world\n');
}).listen(1337, '127.0.0.1');
// We call listen() on the Server object that is returned.
// listen() takes the following params:
// 1. port?: number
// 2. hostname?: string
// 3. backlog?: number
// 4. listeningListener?: Function
// listen() returns a Server object.
// 127.0.0.1 is standard internal IP address of localhost.
// Allows us to make request via localhost:1337
// Execute file in command line;
// It keeps running and listens for requests.
// Give it a request by navigating to localhost:1337 in browser.
// This looks on localhost for a program that
// is listening on port 1337 and gives it HTTP request
// that browser is going to make.
// Node code will be run because request event will be emitted
// and we have server listening and we gave it a function;
// function will be invoked, which will read the request
// and allow me to write the response.
// HTTP response will be built and sent back to the browser,
// and browser will go on and do whatever it wants with it
// (whatever it has been programmed to do with that
// particular type of response).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.