Created
June 2, 2018 15:26
-
-
Save tilfin/7c5fe0fd93e1803d4d7d67e54a8bff80 to your computer and use it in GitHub Desktop.
Static server.js example for ES module
This file contains hidden or 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
// Settings | |
const appRoot = ""; | |
const srcRoot = "src"; | |
const staticRoot = "statics"; | |
const path = require('path'); | |
const Koa = require('koa'); | |
const send = require('koa-send'); | |
const srcAbsPath = path.resolve(__dirname, srcRoot); | |
const staticAbsPath = path.resolve(__dirname, staticRoot); | |
const nodeModulesRoot = path.resolve(__dirname, 'node_modules'); | |
async function sendFile(ctx, pt) { | |
if (pt.startsWith("~")) { | |
// node_modules | |
return await send(ctx, pt.substr(1), { root: nodeModulesRoot }); | |
} else if (pt.startsWith(`${appRoot}/${srcRoot}/`)) { | |
// src | |
pt = pt.substr(srcRoot.length + 1); | |
if (!path.extname(pt)) pt += '.js'; | |
return await send(ctx, pt, { root: srcAbsPath }); | |
} else { | |
// static | |
return await send(ctx, pt, { root: staticAbsPath, index: 'index.html' }); | |
} | |
} | |
function createServer() { | |
const app = new Koa(); | |
app.use(async (ctx, next) => { | |
await next(); | |
// Set cors headers | |
ctx.set('Access-Control-Allow-Origin', '*'); | |
ctx.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); | |
ctx.set('Access-Control-Allow-Headers', 'Content-Type'); | |
}); | |
app.use(async (ctx, next) => { | |
if (!['GET', 'HEAD'].includes(ctx.method)) { | |
ctx.status = 405; | |
ctx.body = "Method now allowed"; | |
return; | |
} | |
let pt = ctx.path; | |
let done = false; | |
if (pt.startsWith(appRoot)) { | |
pt = pt.substr(appRoot.length); | |
try { | |
if (pt.startsWith('/~')) { | |
done = await send(ctx, pt.substr(2), { root: nodeModulesRoot }); | |
} else { | |
done = await sendFile(ctx, pt); | |
} | |
} catch(err) { | |
if (err.status !== 404) throw err; | |
} | |
} else { | |
ctx.status = 404; | |
ctx.body = "Not found"; | |
return; | |
} | |
if (!done) await next(); | |
}); | |
return app; | |
} | |
createServer().listen(process.env.PORT || 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment