Hello world with Node.js HTTP server

Node.js http server

An http server, is a software that listen to requests from users using HTTP protocol and respond with the corresponding content. For example when you enter to youtube using the browser, the browser send an http request to the youtube server which by its turn return the response to the browser who show it to you.

To create a server in Node.js we will use the server module from the core library of Node.Js. But first let's create our server.js file to start writing some code (Since Node.js uses javascript, each file should be of type "js").

const http = require("http");

const server = http.createServer((req, res)=>{
	res.writeHead(200, {'Content-type': 'text/html'});
	res.end("<h1>Hello world</h2>");
}).listen(3000, ()=>console.log("Server listening on port 3000"));

Code explaining

  • require: Used to import some javascript modules written by Node.js, 3rd libraries, or by you to do some specific job. Those modules will export some functions, objects, etc. and by importing them you'll have access to those functionnalies inside your Node.js script.
  • http: is a built-in module created by Node.js which allow us to create server instances and handle http server data.
  • createServer: takes two parameters
    • Callback (Anonymous function executed once the server is up and running) which take two parameters, the user request (data send by user, for example the type of method (get or post), the query parameters and so on) and the response which allow us to dispatch the result to the end user.
    • Port: In which port the server will listen
  • writeHead: Write some header info to the end-user, for example the status code and the content type.
  • end: Will close the response and send the data to the end-user.

Running Node.js code

to run Node.js code we will use the node command followed by the name of the file.

> node server.js
Server listening on port 3000

Running from browser

nodejs http server hello world example

Code refractor and using environment variables for port: process.env

Environment variables are a fundamental part of developing with Node.js, allowing your app to behave differently based on the environment you want them to run in. Wherever your app needs configuration, you use environment variables.

const http = require("http");

//PORT
const normalizePort = val => {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        // named pipe
        return val;
    }

    if (port >= 0) {
        // port number
        return port;
    }

    return false;
};

const port = normalizePort(process.env.PORT || "3000");

//Listening
const onListening = () => {
    const addr = server.address();
    const bind = typeof port === "string" ? "pipe " + port : "port " + port;
    console.log("Listening on " + bind);
};

//Error
const onError = error => {
    console.log(error)
    if (error.syscall !== "listen") {
        throw error;
    }
    const bind = typeof port === "string" ? "pipe " + port : "port " + port;
    switch (error.code) {
        case "EACCES":
            console.error(bind + " requires elevated privileges");
            process.exit(1);
            break;
        case "EADDRINUSE":
            console.error(bind + " is already in use");
            process.exit(1);
            break;
        default:
            throw error;
    }
};


//Server
const server = http.createServer((req, res)=>{
	res.writeHead(200, {'Content-type': 'text/html'});
	res.end("<h1>Hello world</h2>");
});

server.on("error", onError);
server.on("listening", onListening);

server.listen(port);

Running the server

> node server.js

Running the server on different port

Shell

> $env:PORT=5000
> node server.js
Listening on port 5000

Windows CMD

> set PORT=5000
> node server.js
Listening on port 5000

Source code

The full implementation of this article can be found in the GitHub project: Node.js learning