Skip to content

Instantly share code, notes, and snippets.

@zackferrofields
Last active January 8, 2016 13:54
Show Gist options
  • Save zackferrofields/6fec75ab30173d569621 to your computer and use it in GitHub Desktop.
Save zackferrofields/6fec75ab30173d569621 to your computer and use it in GitHub Desktop.
Node static HTTP server
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const PORT = 8000;
http.createServer((req, res) => {
const pathname = url.parse(req.url).pathname;
const isStaticFile = !!path.extname(pathname);
const filePath = path.join(__dirname, isStaticFile ? path.join('static', pathname) : 'views/index.html');
if (!isStaticFile) res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream(filePath)
.on('data', data => res.write(data))
.on('end', () => res.end())
.on('error', () => res.end());
}).listen(PORT);
process.stdout.write(`Running on http://localhost:${PORT} \n`);
console.log('Hello World!');
<!DOCTYPE "html">
<html>
<head>
<link rel="stylesheet" href="/styles/main.css">
</head>
<body>
<h1>Hello World!</h1>
<script src="/scripts/main.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment