0

I have a Node Js local server and several identical html pages. On every page I save some user data input fields saved simply on a text file. My problem is that if the users refresh the page the data from the previous html page is send again and again saved on the text file. Is there a way to prevent this?

var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;

app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + "/public"));
app.use('/images', express.static(__dirname +'/images'));

app.listen(port, function(){
    console.log('server is running on ' + port);
});


app.get('/', function(req, res){
    res.sendfile('intro.html');
});

app.post('/userID', function(req, res){
  //save the userID on a text file
  var userID= req.body.userID + ';';
  var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');

  return res.sendfile('main.html');
});

app.post('/submit', function(req, res){

  res.sendfile('main2.html');
});

Furthermore, I have also a refresh button that does the same as the browser refresh button. I s there a way to avoid the same problem?

  <button>Reset</button>

and its JavaScript:

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('button').addEventListener('click', clickHandler);
    });

    function clickHandler(element) {
          location.reload();
    }

Thank you in advance!

1 Answers1

0

You can use fs.readFile and check if that file contain that userId

If that is not present then append or else dont append

fs.readFile('temporary/userID.txt', function (err, fileData) {
    if (err) throw err;
    if(fileData.indexOf(userID) == -1){
        var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
     }
});

So, the code will be:

app.post('/userID', function(req, res){
  //save the userID on a text file
  var userID= req.body.userID + ';';
  fs.readFile('temporary/userID.txt', function (err, fileData) {
    if (err) throw err;
    if(fileData.indexOf(userID) == -1){
      var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
    }
  });
  return res.sendfile('main.html');
});
Sravan
  • 18,467
  • 3
  • 30
  • 54