const express = require('express');
const fs = require('fs');
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.text({ type: 'text/plain' }));
app.route('/').get((req, res) => {
res.send(`
<div id="myObj">Click Me</div>
<div id="counter">${fs.readFileSync('count.txt').toString() || '0'}</div>
<script>
myObj.onclick = e=> {
var req = new XMLHttpRequest();
req.onreadystatechange = e => {
if(req.readyState == 4 && req.status == 200){
counter.textContent = req.response;
}
};
req.open('POST', 'http://localhost:3000');
req.setRequestHeader('Content-Type', 'text/plain');
req.send('count++');
};
</script>
`);
}).post((req, res) => {
if (req.body === 'count++') {
var count = (Number(fs.readFileSync('count.txt')) + 1).toString();
fs.writeFileSync('count.txt', count);
res.send(count);
}
});
app.listen(3000);
хотя для такой задачи наверное больше socket подойдет