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. variableconst 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...`);
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. variableconst 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...`);