Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
web server in node.js
// A very basic web server in node.js
// Stolen from: Node.js for Front-End Developers by Garann Means (p. 9-10)
var port = 8000;
var serverUrl = "";
var http = require("http");
var path = require("path");
var fs = require("fs");
var checkMimeType = true;
console.log("Starting web server at " + serverUrl + ":" + port);
http.createServer( function(req, res) {
var now = new Date();
var filename = req.url || "index.html";
var ext = path.extname(filename);
var localPath = __dirname;
var validExtensions = {
".html" : "text/html",
".js": "application/javascript",
".css": "text/css",
".txt": "text/plain",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png",
".woff": "application/font-woff",
".woff2": "application/font-woff2"
var validMimeType = true;
var mimeType = validExtensions[ext];
if (checkMimeType) {
validMimeType = validExtensions[ext] != undefined;
if (validMimeType) {
localPath += filename;
fs.exists(localPath, function(exists) {
if(exists) {
console.log("Serving file: " + localPath);
getFile(localPath, res, mimeType);
} else {
console.log("File not found: " + localPath);
} else {
console.log("Invalid file extension detected: " + ext + " (" + filename + ")")
}).listen(port, serverUrl);
function getFile(localPath, res, mimeType) {
fs.readFile(localPath, function(err, contents) {
if(!err) {
res.setHeader("Content-Length", contents.length);
if (mimeType != undefined) {
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
} else {

lili21 commented Dec 13, 2013

line 37:
getFile(localPath, res, isValidExt);

I'm agree with oracle-li

line no 34: path.exists should be fs.exists now

Hi not sure where the now date var is used. just omitted it, thanks

Hi, I used your code to make my html file as a server, but the file cannot show properly and the buttons on the html file don't work. This html file is used to test APIs that send commands to another website which is a client of another node server. When I open this html file locally using browser, it works. Could you give me some advice? Thanks!

Nice One man... Really Good for beginners

line 37 should be isValidExt instead of ext

getFile(localPath, res, isValidExt);

hectorcorrea commented Nov 10, 2016

Thanks for the feedback. I've updated it to address the path.exists() and isValidExt issues that you all reported.

My JSHint says: Use '!==' to compare with 'undefined'

fs.readFile deprecated. You should use fs.access or fs.stat now.

I have replaced the fs.exists part with fs.access;

fs.access(localPath, function(err) {
    if(err) {
        console.log('File not found: ' + localPath);

    console.log('Serving file: ' + localPath);
    getFile(localPath, res, mimeType);

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