import fs from 'fs'; import nomad from './core'; const PORT = 1337; let count = 0; const stats = file => new Promise((resolve, reject) => { fs.stat(file, (err, stat) => err ? reject(err) : resolve(stat)); }); const assets = path => async (req, res, next) => { try { const filePath = `${path}${req.url}`; const stat = await stats(filePath); if (!stat.isFile()) throw new Error('Cannot load directory'); res.statusCode = 200; res.body = fs.createReadStream(filePath); } catch(e) { await next(); } } const app = nomad(); app.use(async (req, res, next) => { const time = Date.now(); console.log(`initiate req ${++count}`); await next(); res.setHeader('Response-Time', `${Date.now() - time}ms`); }); app.use(async (req, res, next) => { try { await next() } catch(e) { res.statusCode = 500; res.body = e.message; } }); app.get(assets(process.cwd())); app.use('/hello', (req, res, next) => { res.statusCode = 200; res.body = 'hello'; }); app.use('/world', (req, res, next) => { res.statusCode = 200; res.body = 'world'; }); app.get('/file', (req, res, next) => { res.statusCode = 200; res.body = fs.createReadStream(`${process.cwd()}/package.json`); }); app.use(() => { throw new Error('Route not found.'); }); app.listen(PORT, () => console.log(`Server started on: ${PORT}`));