0

I created a contact page and the post data of this would be written into a file, but when another person writes on the contact page, the old data gets overwritten with the new one (meaning the old data is lost and I can not help this person) how can I fix this?

My code:

app.post('/process', function(req, res, next){
  console.log('Form : ' + req.query.form);
  console.log('CSRF token : ' + req.body._csrf);
  console.log('Email : ' + req.body.email);
  console.log('Question : ' + req.body.ques);
  res.redirect(303, '/thankyou');
    fs.writeFile('./contactdata/contactdata.txt',
    req.query.form + ':' + req.body._csrf + ':' + req.body.email + ':' + req.body.ques, function(err){
      if(err){
        return console.error(err);
      };
    });
  });

The + ':' is there to seperate stuff.

2 Answers2

1

Instead of using fs.writeFile, use fs.appendFile to add new data to the end of specific file.

hsz
  • 148,279
  • 62
  • 259
  • 315
0

fs.appendFile is what you need to use:

  • It appends Data to an existing file at EOF
  • If the file doesn't exist it is created

app.post('/process', function(req, res, next){
    console.log('Form : ' + req.query.form);
    console.log('CSRF token : ' + req.body._csrf);
    console.log('Email : ' + req.body.email);
    console.log('Question : ' + req.body.ques);
    res.redirect(303, '/thankyou');
      fs.appendFile('./contactdata/contactdata.txt',
      req.query.form + ':' + req.body._csrf + ':' + req.body.email + ':' + req.body.ques, function(err){
        if(err){
          return console.error(err);
        };
      });
    });
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44