Skip to content

Instantly share code, notes, and snippets.

@ricardocanelas
Last active May 14, 2020 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardocanelas/9ae9e21d61705685abebe4c5ee42c858 to your computer and use it in GitHub Desktop.
Save ricardocanelas/9ae9e21d61705685abebe4c5ee42c858 to your computer and use it in GitHub Desktop.
Simple server using http
const http = require('http');
const url = require('url');
const path = require('path')
const fs = require('fs');
const mimeTypes = {
"html": "text/html",
"mp3":"audio/mpeg",
"mp4":"video/mp4",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"
};
const config = {
port: 8080
}
const routes = {
"GET": {
"/": (req, res) => {
res.write('Hello World!');
res.end();
},
"/about": (req, res) => {
res.write('About Page');
res.end();
},
"/contact": (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
const fileStream = fs.createReadStream('./contact.html');
fileStream.pipe(res);
}
}
}
http.createServer(function (req, res) {
const urlParse = url.parse(req.url, true);
const pathname = path.resolve(urlParse.pathname)
// Checking if a route exist
if (routes[req.method]) {
const route = routes[req.method][pathname]
if (route) {
try {
return route(req, res)
} catch (err) {
console.log(err)
res.writeHead(500, {'Content-Type': 'text/html'});
return res.end(`Something happen\n ${JSON.stringify(err, null, 2)}`);
}
}
}
// Checking if the request is a file
const filename = path.join(process.cwd(), urlParse.pathname);
fs.exists(filename, function(exists) {
if(!exists) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
}
const mimeType = mimeTypes[path.extname(filename).split(".")[1]];
res.writeHead(200, {'Content-Type':mimeType});
const fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
});
}).listen(config.port);
console.log(`server running on port ${config.port}`);
const http = require('http');
const url = require('url');
const path = require('path')
const config = { port: 8080 }
const routes = {
"GET": {
"/": (req, res) => {
res.write('Hello World!')
res.end()
},
"/about": (req, res) => {
res.write('About Page')
res.end()
}
}
}
http.createServer(function (req, res) {
const urlParse = url.parse(req.url, true);
const pathname = path.resolve(urlParse.pathname)
if (routes[req.method]) {
const route = routes[req.method][pathname]
if (route) {
route(req, res)
return
}
}
res.write('Page or File Not Found')
res.end()
}).listen(config.port)
console.log(`server running on port ${config.port}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment