Simple NodeJS server for restful API serving files as JSON with no dependencies
const http = require('http');
const fs = require('fs');
const path = require('path');
const port = process.env.PORT || 3000;
http.createServer(function (request, response) {
console.log(`request ${request.url}`)
const filePath = `.${request.url}`;
const contentType = 'application/json';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code == 'ENOENT') {
response.writeHead(404, { 'Content-Type': contentType });
response.end(content, 'utf-8');
} else {
response.writeHead(500);
response.end(`Server error: ${error.code} ..\n`);
response.end();
}
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
})
}).listen(port);
console.log(`Server running at :${port}`);