Skip to content

Instantly share code, notes, and snippets.

@Iainmon
Created May 13, 2021 19:04
Show Gist options
  • Save Iainmon/3d0141a5692c9bb109cef8ac0ed04f13 to your computer and use it in GitHub Desktop.
Save Iainmon/3d0141a5692c9bb109cef8ac0ed04f13 to your computer and use it in GitHub Desktop.
(([http, fs]) => fs.readdir([__dirname, 'public'].join('/'))
.then(names => names.map(name => fs.readFile([__dirname, 'public', name].join('/'))
.then(contents => [name, contents])))
.then(promises => Promise.all(promises))
.then(pairs => [new Map(), pairs])
.then(([assets, pairs]) => [assets, pairs.map(pair => assets.set(...pair))].shift())
.then(assets => [
assets,
[...assets.keys()]
.map(name =>
console.warn(`${['public', name].join('/')} has been loaded into memory.`))
].shift())
.then(assets =>
http.createServer(
(request, response) => (([response, url]) =>
(name =>
(async (dict, key) =>
new Promise((resolve, reject) =>
dict.has(key) ? resolve(dict.get(key)) : reject(key))
)(assets, name)
.then(data => [name, data])
.catch(k => (x => {throw x})(['404.html', assets.get('404.html')]))
)(url == '/' ? 'index.html' : url.substring(1))
.then(([name, data]) => ({ assetName: name, status: 200, reply: data }))
.catch(([name, data]) => ({ assetName: name, status: 404, reply: data }))
.then(({ assetName, status, reply }) =>
({
assetName: assetName,
status: status,
contentType:
[...Object.entries({
'application/json': ['json'],
'text/html': ['html'],
'text/css': ['css'],
'application/javascript': ['js'],
'image/jpeg': ['jpeg', 'jpg']
})
.filter(([header, extensions]) => extensions.includes(assetName.split('.').pop()))
.map(([k, v]) => k)
, 'text/plain'].shift(),
reply: reply,
}))
.then(package => [
package,
package.contentType == 'text/plain' ? console.warn(`Undefined content type for .${extension}!`) : undefined
].shift())
.then(({ assetName, status, contentType, reply }) => [
response.setHeader('Content-Type', contentType),
response.writeHead(status),
response.end(reply),
]))
([response, request.url])
).listen(
process.env.PORT || 3000,
'localhost',
() => console.log(`Server is running on http://localhost:${process.env.PORT || 3000}`)
)))(['http', 'fs']
.map(name => [name, require(name)])
.map(([name, mod]) =>
name == 'fs' ? mod.promises : mod));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment