Skip to content

Instantly share code, notes, and snippets.

@toreylittlefield
Created March 7, 2022 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toreylittlefield/e4f8af043505667c1960f592e5db9d64 to your computer and use it in GitHub Desktop.
Save toreylittlefield/e4f8af043505667c1960f592e5db9d64 to your computer and use it in GitHub Desktop.
Github Profile Views Count With Glitch Express Server
//@ts-check
const express = require("express");
const app = express();
const fs = require("fs");
const FILE_NAME = "count.json";
app.get("/:userName/count.svg", async (req, res, next) => {
const counterFile = await new Promise((resolve, reject) =>
fs.readFile(FILE_NAME, "utf8", (err, data) => {
if (err) {
console.error(err);
reject(err);
return;
}
resolve(JSON.parse(data));
})
);
const counter = counterFile;
console.log({ counter });
const userKey = req.params.userName;
if (userKey in counter) {
counter[userKey] += 1;
} else {
counter[userKey] = 1;
}
const user = counter[userKey];
const svg = `
<svg width="7px" height="7px" viewBox="0 0 10 10" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Count</title>
<text id="0" x="0" y="10" font-family="Courier" font-size="5" font-weight="normal" fill="black" style="fill: coral;">
${user}
</text>
</svg>`;
res.set({
"content-type": "image/svg+xml",
"cache-control": "max-age=0, no-cache, no-store, must-revalidate",
});
res.send(svg);
await new Promise((resolve, reject) =>
fs.writeFile(FILE_NAME, JSON.stringify(counterFile), (err, data) => {
if (err) {
console.error(err);
reject(err);
return;
}
if (data) {
resolve(data);
}
})
);
});
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