Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charudatta10/866657bf8b5143563f146b87c2ae6950 to your computer and use it in GitHub Desktop.
Save charudatta10/866657bf8b5143563f146b87c2ae6950 to your computer and use it in GitHub Desktop.
// This app initially started from Flavio Copes analytics example
// but diverged quite a bit to generate images as well as track views
// https://flaviocopes.com/count-visits-static-site/
const express = require('express')
const app = express()
// no db - so global var to keep track of count
let counter = 0
function getCountImage(count) {
// This is not the greatest way for generating an SVG but it'll do for now
const countArray = count.toString().padStart(6, '0').split('');
const parts = countArray.reduce((acc, next, index) => `
${acc}
<rect id="Rectangle" fill="#000000" x="${index * 32}" y="0.5" width="29" height="29"></rect>
<text id="0" font-family="Courier" font-size="24" font-weight="normal" fill="#00FF13">
<tspan x="${index * 32 + 7}" y="22">${next}</tspan>
</text>
`, '');
return `<?xml version="1.0" encoding="UTF-8"?>
<svg width="189px" height="30px" viewBox="0 0 189 30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Count</title>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
${parts}
</g>
</svg>
`
}
// get the image
app.get('/count.svg', (req, res) => {
counter++;
// This helps with GitHub's image cache
// see more: https://rushter.com/counter.svg
res.set({
'content-type': 'image/svg+xml',
'cache-control': 'max-age=0, no-cache, no-store, must-revalidate'
})
// Send the generated SVG as the result
res.send(getCountImage(counter));
})
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment