Created
February 10, 2019 14:39
-
-
Save antelle/12d6073db5a1da79428841ef98394694 to your computer and use it in GitHub Desktop.
Simple web server with node.js
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
const http = require('http'); | |
const path = require('path'); | |
const fs = require('fs'); | |
const port = 8080; | |
const server = http.createServer((req, resp) => { | |
const filePathPart = req.url.substr(1) || 'index.html'; | |
const filePath = path.resolve(__dirname, filePathPart); | |
if (!filePath.startsWith(__dirname)) { | |
resp.writeHead(403); | |
resp.end('Forbidden'); | |
return; | |
} | |
if (!fs.existsSync(filePath)) { | |
resp.writeHead(404); | |
resp.end('Not found'); | |
return; | |
} | |
const data = fs.readFileSync(filePath, 'utf8'); | |
resp.writeHead(200, 'OK', { | |
'Content-Type': getContentType(path.extname(filePath)), | |
'Cache-Control': 'no-cache, no-store, must-revalidate', | |
Pragma: 'no-cache', | |
Expires: '0' | |
}); | |
resp.end(data); | |
}); | |
server.listen(port, err => { | |
if (err) { | |
return console.error('Error', err); | |
} | |
console.log(`The server is running: http://127.0.0.1:${port}`); | |
}); | |
function getContentType(ext) { | |
switch (ext) { | |
case '.html': | |
return 'text/html'; | |
case '.js': | |
return 'text/javascript'; | |
case '.css': | |
return 'text/css'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment