Framework-less node server
suggest changevar http = require('http');
var fs = require('fs');
var path = require('path');
var root = path.resolve('.');
http.createServer(function (request, response) {
console.log('request ', request.url);
// request.url is untrusted. Strip a leading slash so path.join does not
// treat it as absolute, then keep the file inside this directory.
var requestPath = request.url.split('?')[0];
if (requestPath === '/')
requestPath = '/index.html';
var filePath = path.normalize(path.join(root, requestPath.replace(/^[/\\]+/, '')));
if (filePath !== root && filePath.indexOf(root + path.sep) !== 0) {
response.writeHead(400);
response.end('Bad request');
return;
}
var extname = String(path.extname(filePath)).toLowerCase();
var mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.svg': 'image/svg+xml'
};
var contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, function(error, content) {
if (error) {
if (error.code == 'ENOENT') {
fs.readFile(path.join(root, '404.html'), function(err404, page) {
response.writeHead(404, { 'Content-Type': 'text/html' });
response.end(page || 'Not found');
});
} else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
}
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content);
}
});
}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents