Last active
August 9, 2024 07:01
-
-
Save sochix/475c9d6b32780c56db909c72bde0f150 to your computer and use it in GitHub Desktop.
Counting requests in your Node.js+Express application
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
const app = require('express')() | |
const getRoute = (req) => { | |
const route = req.route ? req.route.path : '' // check if the handler exist | |
const baseUrl = req.baseUrl ? req.baseUrl : '' // adding the base url if the handler is child of other handler | |
return route ? `${baseUrl === '/' ? '' : baseUrl}${route}` : 'unknown route' | |
} | |
const fs = require('fs') | |
const FILE_PATH = 'stats.json' | |
// read json object from file | |
const readStats = () => { | |
let result = {} | |
try { | |
result = JSON.parse(fs.readFileSync(FILE_PATH)) | |
} catch (err) { | |
console.error(err) | |
} | |
return result | |
} | |
// dump json object to file | |
const dumpStats = (stats) => { | |
try { | |
fs.writeFileSync(FILE_PATH, JSON.stringify(stats), { flag: 'w+' }) | |
} catch (err) { | |
console.error(err) | |
} | |
} | |
app.use((req, res, next) => { | |
res.on('finish', () => { | |
const stats = readStats() | |
const event = `${req.method} ${getRoute(req)} ${res.statusCode}` | |
stats[event] = stats[event] ? stats[event] + 1 : 1 | |
dumpStats(stats) | |
}) | |
next() | |
}) | |
app.get('/api/', (req, res) => { | |
res.sendStatus(200) | |
}) | |
app.get('/stats/', (req, res) => { | |
res.json(readStats()) | |
}) | |
app.listen(3000, () => { | |
console.log('Server started') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment