Skip to content

Instantly share code, notes, and snippets.

@trungnghia112
Created May 31, 2016 03:22
Show Gist options
  • Save trungnghia112/a2f1c142c165fe3a036c368f0fe0e1a7 to your computer and use it in GitHub Desktop.
Save trungnghia112/a2f1c142c165fe3a036c368f0fe0e1a7 to your computer and use it in GitHub Desktop.
// node static-server.js
var http = require('http');
var fs = require('fs');
var path = require('path');
var port = 4000;
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.wav':
contentType = 'audio/wav';
break;
}
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');
}
});
}).listen(port);
console.log('Server running at http://localhost:' + port + '/\nCTRL + C to shutdown');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment