Created
August 1, 2014 05:44
-
-
Save Venemo/0639046c4bff8006e08c to your computer and use it in GitHub Desktop.
Simple Node.js file server
This file contains 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
// | |
// Very simple Node.js file server by Timur Kristóf | |
// | |
var http = require('http'); | |
var url = require('url'); | |
var fs = require('fs'); | |
var mime = require('mime'); | |
// Figure out port number | |
var portNumber = process.env.PORT || 1337; | |
// Create HTTP server | |
var server = http.createServer(function (req, res) { | |
// Examine URL, get requested file path | |
var currentUrl = url.parse(req.url, true); | |
if (currentUrl.pathname === "/" || currentUrl.pathname.indexOf("..") > -1) { | |
currentUrl.pathname = "/index.html"; | |
} | |
var filePath = __dirname + currentUrl.pathname; | |
//console.log("requested:", req.url, filePath); | |
// Check if file exists | |
fs.exists(filePath, function (exists) { | |
if (!exists) { | |
// Return with 404 | |
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); | |
res.end("There is no such thing on this server."); | |
return; | |
} | |
// Write response head | |
res.writeHead(200, { 'Content-Type': mime.lookup(filePath) }); | |
// Pipe the file stream into the response stream | |
var fileStream = fs.createReadStream(filePath); | |
fileStream.pipe(res); | |
}); | |
}); | |
// Start server | |
server.listen(portNumber); | |
console.log("web server listening on: " + portNumber); |
This file contains 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
{ | |
"name": "simple-file-server", | |
"description": "The simplest possible file server", | |
"author": "Timur Kristóf", | |
"version": "1.0.0", | |
"dependencies": { | |
"mime": "*" | |
}, | |
"engine": "node >= 0.8.0" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment