Skip to content

Instantly share code, notes, and snippets.

@codeofnode
Last active July 30, 2018 09:01
Show Gist options
  • Save codeofnode/28138e362084df1d86ba1a4b0cec10f5 to your computer and use it in GitHub Desktop.
Save codeofnode/28138e362084df1d86ba1a4b0cec10f5 to your computer and use it in GitHub Desktop.
Pure node js server where routes represents your directories
const { createServer } = require('http')
const { createReadStream } = require('fs')
const { parse } = require('url')
const { extname, resolve } = require('path')
const PORT = 9000
const HOST = '0.0.0.0'
const DOC_HANDLER = process.env.J2S_DOC_HANDLER || '_doc'
const DOC_CHECK = process.env.J2S_DOC_CHECK
const BASE_PATH = process.env.J2S_BASE_PATH || '/v0'
createServer((req, res) => {
const parsed = parse(req.url, true)
req.query = parsed.query
const reqMethod = req.method.toLowerCase()
if (!(parsed.pathname.startsWith(BASE_PATH))) {
res.writeHead(404, { 'Content-Type': 'application/json' });
return res.end('{"error":"Service not found"}')
}
const paths = parsed.pathname.slice(BASE_PATH.length + 1).split('/')
const pathLength = paths.length;
async function resolveResponse() {
const jsonRes = {}
for (let ind = 0; ind < pathLength; ind++) {
let module;
const pathParams = {}
if (ind % 2 === 1) {
pathParams[paths[ind-1].slice(0,-1) + 'Id'] = paths[ind]
if (DOC_CHECK === '1') {
try {
module = require(resolve(...(paths.slice(0, ind+1))))
} catch (er) {
if (er.code === 'MODULE_NOT_FOUND') {
module = require(resolve(...(paths.slice(0, ind).concat([DOC_HANDLER]))))
} else {
throw er
}
}
} else {
module = require(resolve(...(paths.slice(0, ind).concat([DOC_HANDLER]))))
}
} else {
module = require(resolve(...(paths.slice(0, ind+1))))
}
await module[reqMethod](req, jsonRes, pathParams)
}
return jsonRes
}
resolveResponse().then((jsonRes) => {
if (jsonRes.hasOwnProperty('_file')) {
const fileExt = String(extname(jsonRes._file)).toLowerCase();
res.writeHead(jsonRes._statusCode || 200, {
'Content-disposition': `attachment; filename=${jsonRes._file}`,
'Content-Type': `application/${fileExt}`
});
const filestream = createReadStream(jsonRes._file);
filestream.pipe(res);
} else {
res.writeHead(jsonRes._statusCode || 200, { 'Content-Type': 'application/json' });
const toSend = jsonRes.data;
if (typeof toSend === 'string') {
res.end(`{"message":"${toSend}"}`)
} else {
res.end(JSON.stringify(toSend))
}
}
}).catch((er) => {
// console.error(er)
if (er.code == 'MODULE_NOT_FOUND') {
er._statusCode = 404
er.message = 'Route not found.'
} else if (er.message === 'module[reqMethod] is not a function') {
er._statusCode = 405
er.message = 'Route method not found.'
}
res.writeHead(er._statusCode || 400, { 'Content-Type': 'application/json' })
res.end(`{"error":"${er.message}"}`)
});
}).listen(PORT, HOST, () => {
console.log(`Server running at http://${HOST}:${PORT}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment