Last active
March 23, 2025 15:28
-
-
Save veganaize/fc3b9aa393ca688a284c54caf43a3fc3 to your computer and use it in GitHub Desktop.
Most basic Node.js web server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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...')}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Minimal http server using no 3rd-party frameworks, handles 404 errors, adds trailing slashes, and allows query strings,
Create a
public_html/
subfolder, inside thewebserver.js
file's folder, and place all site content in it.