Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fromanegg.com - How to make a Node.js static file server - Part 1
var http = require('http'),
path = require('path'),
fs = require('fs'),
util = require('util');
http.createServer(_handler).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
function _handler(req, res) {
var root = "..",
url = "",
contentType = "text/plain",
filePath = "";
if (req.method !== 'GET') { //If the request method doesn't equal 'GET'
res.writeHead(405); //Write the HTTP status to the response head
res.end('Unsupported request method', 'utf8'); //End and send the response
return;
}
if ('.' + req.url !== './') {
filePath = root + req.url;
path.exists(filePath, serveRequestedFile);
} else {
res.writeHead(400);
res.end('A file must be requested', 'utf8');
return;
}
function serveRequestedFile(file) {
if (file === false) {
res.writeHead(404);
res.end();
return;
}
var stream = fs.createReadStream(filePath);
stream.on('error', function(error) {
res.writeHead(500);
res.end();
return;
});
var mimeTypes = {
'.js' : 'text/javascript',
'.css' : 'text/css',
'.gif' : 'image/gif'
};
contentType = mimeTypes[path.extname(filePath)];
res.setHeader('Content-Type', contentType);
res.writeHead(200);
util.pump(stream, res, function(error) {
//Only called when the res is closed or an error occurs
res.end();
return;
});
}
}
@rognoni

This comment has been minimized.

Copy link

commented Aug 12, 2014

Good, I see this message "A file must be requested" :-)
The Part 2 shows the filesystem with the ability to browse the sub-folders, right?

Replaced two parts of your code with:

//path.exists(filePath, serveRequestedFile);
fs.exists(filePath, serveRequestedFile);
/*util.pump(stream, res, function(error) {
    //Only called when the res is closed or an error occurs
    res.end();
    return;
});*/
stream.pipe(res);
@alpha1125

This comment has been minimized.

Copy link

commented Aug 23, 2014

Just so anyone looking, notice the var root = "..". That was trowing me off... as the files could not be found.

I changed it to root = "./" and I was able to serve files in the current path...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.