Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active April 26, 2019 07:23
Show Gist options
  • Save davidgilbertson/9ecab8ff5f9b5395b3fc3c873dfa0413 to your computer and use it in GitHub Desktop.
Save davidgilbertson/9ecab8ff5f9b5395b3fc3c873dfa0413 to your computer and use it in GitHub Desktop.
const http = require('http');
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const PORT = 3001;
const STATIC_DIRECTORY = path.resolve(__dirname, '../build/');
const cache = {};
const getStaticFile = fileName => {
if (fileName in cache) return cache[fileName];
const fileBuffer = fs.readFileSync(path.resolve(STATIC_DIRECTORY, fileName.replace(/^\//, '')));
const compressedFile = zlib.gzipSync(fileBuffer.toString(), {
level: zlib.constants.Z_BEST_COMPRESSION,
});
cache[fileName] = compressedFile;
return compressedFile;
};
const getContentType = fileName => {
const contentTypes = {
'.js': 'application/javascript',
'.css': 'text/css',
'.png': 'image/png',
'.woff': 'font/woff; charset=UTF-8',
'.woff2': 'font/woff2',
};
const extensionMatch = fileName.match(/\.[a-zA-Z]*$/);
return extensionMatch ? contentTypes[extensionMatch[0]] : null;
};
const server = http.createServer((req, res) => {
const requestPath = req.url.replace(/\?.*/, '').replace('/connect', '/');
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('status', 200);
if (requestPath === '/') {
res.setHeader('Content-Type', 'text/html');
res.end(getStaticFile('index.html'));
return;
}
res.setHeader('Cache-Control', 'max-age=31536000');
const contentType = getContentType(requestPath);
if (contentType) res.setHeader('Content-Type', contentType);
const file = getStaticFile(requestPath);
if (file) {
setTimeout(() => {
res.end(file);
}, 100);
} else {
res.setHeader('status', 404);
res.end(`<h1>No ${requestPath} for you!</h1>`);
}
});
server.listen(PORT);
console.info(`Server is probably ready on http://localhost:${PORT}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment