Skip to content

Instantly share code, notes, and snippets.

@khalid32
Created October 22, 2017 10:35
Show Gist options
  • Select an option

  • Save khalid32/6aca6f3620587160b42b0370478eee7c to your computer and use it in GitHub Desktop.

Select an option

Save khalid32/6aca6f3620587160b42b0370478eee7c to your computer and use it in GitHub Desktop.
a basic server with nodejs(no express).
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const mimeTypes = {
'html': 'text/html',
'jpeg': 'image/jpeg',
'jpg': 'image/jpg',
'png': 'image/png',
'js': 'text/javascript',
'css': 'text/css',
}
http.createServer(function(req, res){
let uri = url.parse(req.url).pathname;
let fileName = path.join(process.cwd(), unescape(uri));
console.log('Loading' + uri);
let stats;
try{
stats = fs.lstatSync(fileName);
}catch(err){
res.writeHead(404, {'Content-type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
};
if(stats.isFile()){
let mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
res.writeHead(200, {'Content-type': mimeType});
let fileStream = fs.createReadStream(fileName);
fileStream.pipe(res);
}else if(stats.isDirectory()){
res.writeHead('302', {
'Location': 'index.html' // initial page
});
res.end();
}else{
res.writeHead('500', {
'Content-type': 'text/plain'
});
res.write('500 Internal Error!');
res.end();
}
}).listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment