Skip to content

Instantly share code, notes, and snippets.

@sochix
Last active January 20, 2023 06:39
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sochix/475c9d6b32780c56db909c72bde0f150 to your computer and use it in GitHub Desktop.
Save sochix/475c9d6b32780c56db909c72bde0f150 to your computer and use it in GitHub Desktop.
Counting requests in your Node.js+Express application
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