Created
August 1, 2017 03:32
-
-
Save pl12133/9b16e25a15d7b3306586faca9897a237 to your computer and use it in GitHub Desktop.
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
const http = require('http'); | |
const path = require('path'); | |
const fs = require('fs'); | |
const port = process.env.PORT || 8080; | |
const host = process.env.HOST || '0.0.0.0'; | |
const publicPath = __dirname; | |
function serveStatic(publicPath) { | |
return function(request, response) { | |
let url = '.' + request.url; | |
// TODO: Should stat for directory listing. | |
if (!fs.existsSync(url)) { | |
response.statusCode = 404; | |
response.end(); | |
return; | |
} | |
console.log('Found:', url); | |
fs.readFile(url, 'utf-8', (err, data) => { | |
if (err) { | |
response.statusCode = 500; | |
response.end(); | |
return; | |
} | |
response.statusCode = 200; | |
response.end(data); | |
}); | |
} | |
} | |
const app = (function connect() { | |
let middlewares = []; | |
return { | |
use(fn) { | |
middlewares.push(fn); | |
}, | |
listen(port, host) { | |
const server = http.createServer(function connected(request, response) { | |
console.log(middlewares.length); | |
if (middlewares.length === 0) { | |
console.error('You need to define at least one middleware...'); | |
process.exit(1); | |
return; | |
} | |
middlewares.reduce((previous, current) => { | |
return (req, res, next = function() {}) => previous(req, res, current) | |
})(request, response) | |
}); | |
server.listen(port, host); | |
} | |
}; | |
})() | |
app.use(serveStatic(publicPath)); | |
app.listen(port, host) | |
console.log('Serving files from ' + publicPath); | |
console.log('server started on ' + host + ':' + port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment