How works a Node.js file server

Node.js can load pages or applications from a browser using a simple server script.

The script that we present is no different in its operation of the various scripts posted on the official site or in different "tutorials" or pseudo-tutorials about Node.js.
I say pseudo-tutorial because programmers generally do not differentiate between a manual that explains how to use a thing and a tutorial that teaches how it works, in stages and from simple to complex.
When a programmer adds comments to a listing, it is a "tutorial". Maybe not, and the source code itself, is it written to be easily understood?
This is particularly compelling in the case of Node.js since all demo scripts are written in a recursive form that forces the reader to think like a processor, that is the ultimate goal of hackers apparently.

So I rewrote the page server by breaking down the script into elementary functions, to better understand how it works.
But in fact my goal is to take a first step towards a more elaborate script, a server of tools running locally and using web pages as interfaces, and in backend executable files, binaries or not.

1) Creating the server

var server = http.createServer(getFilename);
server.listen(1000);
console.log("Server available...");

The createServer parameter is a callback to be activated when a browser connects to port 1000, with a filename as a parameter. For example by typing in the URL bar of a browser:

127.0.0.1:1000/page.html

2) URL parsing and transmission of the file name to the system

function getFilename(request, response)
{
  var urlpath = url.parse(request.url).pathname;
  var localpath = path.join(process.cwd(), urlpath);
  fs.exists(localpath, function(result) { getFile(result, response, localpath)});
}

This function extracts the path from the URL and passes this parameter to a second function that will read the file on the server or the local computer.
For this we use the url and path modules.

3) Reading the file

function getFile(exists, response, localpath)
{
  if(!exists) return sendError(404, '404 Not Found', response);
  fs.readFile(localpath, "binary",
    function(err, file){ sendFile(err, file, response);});
}

The file is read by the fs module that performs common  functions on the file system, except the execution of programs that requires another module. Our sendFile function is called by readFile in the fs module.

4) Sending the page

function sendFile(err, file, response)
{
  if(err) return sendError(500, err, response);
  response.writeHead(200);
  response.write(file, "binary");
  response.end();
} 

The contents of the file is sent to the browser that displays it. This is done by the response object created in conjunction with the server and that is transmitted to each function.

5) List of  modules used

http = require("http");
path = require("path");
url = require("url");
fs = require("fs");

We saw the role of each of them before, except http that we saw in the introduction, that lets you use the HTTP protocol to exchange data between server and browser (or other user agent).

6) The full script

http = require("http"),
path = require("path"),
url = require("url"),
fs = require("fs");

function sendError(errCode, errString, response)
{
  response.writeHead(errCode, {"Content-Type": "text/plain"});
  response.write(errString + "\n");
  response.end();
  return;
}

function sendFile(err, file, response)
{
  if(err) return sendError(500, err, response);
  response.writeHead(200);
  response.write(file, "binary");
  response.end();
}

function getFile(exists, response, localpath)
{
  if(!exists) return sendError(404, '404 Not Found', response);
  fs.readFile(localpath, "binary",
   function(err, file){ sendFile(err, file, response);});
}

function getFilename(request, response)
{
  var urlpath = url.parse(request.url).pathname; // following domain or IP and port
  var localpath = path.join(process.cwd(), urlpath); // if we are at root
  fs.exists(localpath, function(result) { getFile(result, response, localpath)});
}

var server = http.createServer(getFilename);
server.listen(1000);
console.log("Server available...");  

You can test this basic server by loading the file page.html in the archive. The  source code of the script is the server.js file.

Previously: Introducing Node.js. System description and the interest to use it.
The next step is running locally a PHP program from the browser with Node.js