«®»
Home About Work Contact Quotes

Hello Node.js!

Prerequisite: JavaScript knowledge, I'd say you need to at least understand the server-client model and how the HTTP protocol works. that should be enough to get you started if you already know JS. Node installation steps can be found here - https://nodejs.org/

Simple hello world program as a first example has become the standard in the programming literature. This article will go through hello world example for both terminal and an http server.

Then we'll shift gears up and go through real examples that teaches you enough to write your own web application using node.js. Comments in code explain how it works and text around it explains what it does and how to test it.

Hello Terminal

Create a javascript file like hello-terminal.js and add following line of code. You can run it with command node hello-terminal.js

//Call the console.log function.
console.log("Hello Terminal");

Hello HTTP

Our next example will let you create a simple HTTP server that responds to every request with the plain text message "Hello HTTP".

//Load the http module to create an http server
var http = require("http");

//Configure our HTTP server to respond with Hello HTTP to all requests.
http.createServer(function (req,res) {
	if (req.url=="/") {
		res.writeHead(200,{"Content-type":"text/plain"});
		res.end("Hello HTTP");
	};
//Listen on port 5000, IP defaults to 127.0.0.1
}).listen(5000,"127.0.0.1");

//Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:5000/");

Create a javascript file like hello-http.js and add your code. You can run it with command node hello-http.js