Programming Web server with Node.js



Basic Web server programming

The ability of Node.js is the quick programming of a Web server.

import * as file_system from 'fs';
import * as http from 'http';

const port = process.env['PORT'] || 8080; // Env. variable

const server = http.createServer((request, response) => {
    response.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
    file_system.readFile('./index.html', null, function (error, data) {
        if (error) {
            response.writeHead(404);
            response.write("Whoops! './index.html' not found...");
        } else
            response.write(data);
        response.end();
    });
}).listen(port);
console.log(`Server ready to accept requests on port ${port}... ctrl + C to abort...`);
Web server programming with Express

Express is the most famous library for Node.js to go beyond basic Web server programming. Typically, Express supports routing facilities through the express.Router object type.

import * as path from "path";

import * as express from 'express';

const port = process.env['PORT'] || 8080; // Env. variable

const router: express.Router = express.Router();
const my_Web_application = express();
my_Web_application.use('/', router);
router.get('/', (request, response) => { // Without router: 'my_Web_application.get('/', (request, response) => { ...'
    response.setHeader("Content-Type", "text/html; charset=utf-8");
    response.statusCode = 200;
    response.sendFile(path.join(path.resolve(__dirname, '..') + path.sep + 'index.html'));
});
const server = my_Web_application.listen(port);
console.log(`Server ready to accept requests on port ${port}... ctrl + C to abort...`);
Serving static pages from Node.js Web server based on Express here
import * as path from "path";

import * as express from 'express';

const port = process.env['PORT'] || 8080; // Env. variable

const router: express.Router = express.Router();
const my_Web_application = express();

console.log(__dirname + path.sep + 'static'); // https://expressjs.com/en/starter/static-files.html

my_Web_application.use(express.static('static')); // This serves resources from 'static' folder...
my_Web_application.use('/', router);
router.get('/', (request, response) => {
    response.sendFile(path.join(path.resolve(__dirname, '..') + path.sep + 'index.html'));
});
// Test: http://localhost:8080/Franck
router.get('/Franck', (request, response) => {
    response.sendFile(path.join(path.resolve(__dirname, '..') + path.sep + 'static/Franck.jpg'));
});
// Test: http://localhost:8080/Static_page
router.get('/Static_page', (request, response) => {
    response.sendFile(path.join(path.resolve(__dirname, '..') + path.sep + 'static/Static_page.html'));
});
const server = my_Web_application.listen(port);

Download Server.Node.js.ts.zip