Skip to content

Instantly share code, notes, and snippets.

@veganaize
Last active September 13, 2020 11:52
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 veganaize/fc3b9aa393ca688a284c54caf43a3fc3 to your computer and use it in GitHub Desktop.
Save veganaize/fc3b9aa393ca688a284c54caf43a3fc3 to your computer and use it in GitHub Desktop.
Most basic Node.js web server
var fs = require('fs');
require('http').createServer(function(request, response) {
var path = 'public_html'+ request.url.slice(0,
(request.url.indexOf('?')+1 || request.url.length+1) - 1);
fs.stat(path, function(bad_path, path_stat) {
if (bad_path) respond(404);
else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
response.setHeader('Location', path.slice(11)+'/');
respond(301);
} else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
function(bad_file, file_content) {
if (bad_file) respond(404);
else respond(200, file_content);
});
});
function respond(status, content) {
response.statusCode = status;
response.end(content);
}
}).listen(80, function(){console.log('Server running on port 80...')});
@veganaize
Copy link
Author

veganaize commented Sep 10, 2020

Minimal http server using no 3rd-party frameworks, handles 404 errors, adds trailing slashes, and allows query strings,

Create a public_html/ subfolder, inside the webserver.js file's folder, and place all site content in it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment