Skip to content

Instantly share code, notes, and snippets.

@antelle
Created February 10, 2019 14:39
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 antelle/12d6073db5a1da79428841ef98394694 to your computer and use it in GitHub Desktop.
Save antelle/12d6073db5a1da79428841ef98394694 to your computer and use it in GitHub Desktop.
Simple web server with node.js
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