Skip to content

Instantly share code, notes, and snippets.

@EyeOfMidas
Created October 12, 2020 13:49
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 EyeOfMidas/c19e9afef6c9db823afc2da2de750465 to your computer and use it in GitHub Desktop.
Save EyeOfMidas/c19e9afef6c9db823afc2da2de750465 to your computer and use it in GitHub Desktop.
// Example minimal server from StackOverflow comment by user B T (https://stackoverflow.com/users/122422/b-t)
// https://stackoverflow.com/questions/6084360/using-node-js-as-a-simple-web-server/26354478#26354478
//
// run the server using `node server.js` and you can access any files that are in the same directory.
// in a browser, visit http://localhost:9615/[filename]
// example url (self reference) http://localhost:9615/server.js
var http = require('http')
var url = require('url')
var fs = require('fs')
var path = require('path')
var baseDirectory = __dirname // or whatever base directory you want
var port = 9615
http.createServer(function (request, response) {
try {
var requestUrl = url.parse(request.url)
// need to use path.normalize so people can't access directories underneath baseDirectory
var fsPath = baseDirectory+path.normalize(requestUrl.pathname)
var fileStream = fs.createReadStream(fsPath)
fileStream.pipe(response)
fileStream.on('open', function() {
response.writeHead(200)
})
fileStream.on('error',function(e) {
response.writeHead(404) // assume the file doesn't exist
response.end()
})
} catch(e) {
response.writeHead(500)
response.end() // end the response so browsers don't hang
console.log(e.stack)
}
}).listen(port)
console.log("listening on port "+port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment