Last active
December 26, 2019 02:00
-
-
Save maburdi94/0511d9e01e2135c5c63dd26151999d82 to your computer and use it in GitHub Desktop.
Node HTTP/2 Web Server w/ streams
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 http2 = require('http2'); | |
const fs = require('fs'); | |
const zlib = require('zlib'); | |
let mimeTypes = require('mime-types'); | |
const server = http2.createServer(onRequest); | |
function getAsyncFileStream(filePath) { | |
return new Promise((resolve, reject) => { | |
let fileStream = fs.createReadStream(filePath); | |
fileStream.once('error', reject); | |
fileStream.once('readable', () => resolve(fileStream)); | |
}); | |
} | |
async function onRequest(request, response) { | |
try { | |
// If not GET, skip to path matching. | |
if (request.method !== 'GET') throw request; | |
// Try to resolve request to a file. If file does not exist, throw error. | |
let fileStream = await getAsyncFileStream(request.url); | |
// Response status and Gzip headers | |
response.writeHead(200, { | |
'content-encoding': 'gzip', | |
'content-type': mimeTypes.lookup(request.url) || 'application/octet-stream' | |
}); | |
// Gzip compress | |
fileStream.pipe(zlib.createGzip()).pipe(response); | |
} catch { | |
try { | |
if (/^\/login/.test(request.url)) { | |
loginRouteHandler(request, response); | |
return; | |
} | |
// Check for user authenticated. Redirect unauthenticated users to login page. | |
if (!auth(request, response)) { | |
response.writeHead(301, {Location: '/login'}); | |
response.end(); | |
return; | |
} | |
if (request.url === '/') { | |
let fileStream = await getAsyncFileStream('inventory/index.html'); | |
response.writeHead(200, { | |
'content-encoding': 'gzip', | |
'content-type': mimeTypes.lookup(request.url) || 'application/octet-stream' | |
}); | |
fileStream.pipe(zlib.createGzip()).pipe(response); | |
return; | |
} | |
if (/^\/someRoute/.test(request.url)) { | |
someRouteHandler(request, response); | |
return; | |
} else if (/^\/someOtherRoute/.test(request.url)) { | |
someOtherRouteHandler(request, response); | |
return; | |
} | |
// else if ... | |
// If no path found is found to match the request, | |
// respond with a 404 Http error. | |
response.statusCode = 404; | |
response.end('Resource not found'); | |
} catch { | |
// If an error occurred in the route or controller logic, | |
// catch the error and respond with a 500 Http error. | |
response.statusCode = 500; | |
response.end('Internal error'); | |
} | |
} | |
} | |
module.exports.server = server; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment