Basic Node server.js file example
This is a simple server.js file that could render web pages on a remote web host.
const http = require('http'),
fs = require('fs'),
path = require('path');
const mimeTypes = {
".html": "text/html",
".txt": "text/html",
".js": "text/javascript",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpg",
".svg": "application/image/svg+xml",
".json": "application/json"
};
let handleRequest = (request, response) => {
// path to your static files relative to this file
const basePath = "./public";
let filePath = basePath + request.url;
// use index.html files when the paths are ending with '/'
if( filePath.substr(-1) === "/" ) {
filePath = filePath + '/index.html';
}
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
if (extname === '.html') {
// serve html files
filePath = fs.readFileSync(filePath);
response.writeHead(200, {"Content-Type": contentType});
response.end(filePath, 'utf-8');
} else {
// read other files
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT') {
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
};
let port = 80;
if (process.env.NODE_ENV === 'dev') {
console.log('Dev Server');
port = 8080;
} else {
console.log('Prod Server');
}
http.createServer(handleRequest).listen(port);
Last updated: Feb 7th 2020.