vanilla js http server

Solutions on MaxInterview for vanilla js http server by the best coders in the world

showing results for - "vanilla js http server"
Manuel
03 Jan 2017
1var http = require('http');
2var fs = require('fs');
3var path = require('path');
4
5http.createServer(function (request, response) {
6    console.log('request ', request.url);
7
8    var filePath = '.' + request.url;
9    if (filePath == './') {
10        filePath = './index.html';
11    }
12
13    var extname = String(path.extname(filePath)).toLowerCase();
14    var mimeTypes = {
15        '.html': 'text/html',
16        '.js': 'text/javascript',
17        '.css': 'text/css',
18        '.json': 'application/json',
19        '.png': 'image/png',
20        '.jpg': 'image/jpg',
21        '.gif': 'image/gif',
22        '.svg': 'image/svg+xml',
23        '.wav': 'audio/wav',
24        '.mp4': 'video/mp4',
25        '.woff': 'application/font-woff',
26        '.ttf': 'application/font-ttf',
27        '.eot': 'application/vnd.ms-fontobject',
28        '.otf': 'application/font-otf',
29        '.wasm': 'application/wasm'
30    };
31
32    var contentType = mimeTypes[extname] || 'application/octet-stream';
33
34    fs.readFile(filePath, function(error, content) {
35        if (error) {
36            if(error.code == 'ENOENT') {
37                fs.readFile('./404.html', function(error, content) {
38                    response.writeHead(404, { 'Content-Type': 'text/html' });
39                    response.end(content, 'utf-8');
40                });
41            }
42            else {
43                response.writeHead(500);
44                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
45            }
46        }
47        else {
48            response.writeHead(200, { 'Content-Type': contentType });
49            response.end(content, 'utf-8');
50        }
51    });
52
53}).listen(8125);
54console.log('Server running at http://127.0.0.1:8125/');