Initially …

Let us dive in at the deep end first. Somewhere on your hard drive, you create a project folder, and navigate to that folder with cd.

Example 15.1. Write a Web Server. server.js
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer(function (req, res) {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World!\nBlåbærgrød\n');
});

server.listen(port, hostname, function () {
  console.log(`Server running at http://${hostname}:${port}/`);
});

When the file is saved in your project folder. You issue the following command on the CLI:

node server

or

node server.js

Whatever is more convenient. Then navigate to http://localhost:3000 with your browser.


Example 15.2. Let's Write a Slightly Different Web Server. servera.js
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer(function (req, res) {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.end('Hello World!\nBlåbærgrød\n');
});

server.listen(port, hostname, function () {
  console.log(`Server running at http://${hostname}:${port}/`);
});

When the file is saved in your project folder. You issue the following command on the CLI:

node servera

or

node servera.js

Whatever is more convenient. Then navigate to http://localhost:3000 with your browser.


This is amazing. A webserver in 14, well really only 11, lines of code. This is what we shall work with in this part of the course materials. Who needs Apache? Sorry ;)

There's a hidden message in our showing you two versions: If you need national language characters in your service, do not forget the charset in your HTTP header.