0

I try to save file on desktop and clear it after saving inside my application. I use Node.js and Express in my application. I got data from MongoDB and use fs.appendFile to save neccessary data to file. Then I use button to download saved information. Here is my code(search.ejs):

<div class="fileInfo" id="fileInfo">
  <a href="files/2pac.doc"  type="text/doc" charset="utf-8" download="2pac.doc">
  <button type="button" class="btn btn-md saveToFile" id="saveToFile">
    <!-- style="display:none;" id="saveToFile" -->
    <i class="fa fa-download"></i>
    Зберегти у файл
  </button>
<!-- </a> -->
</div>

Then I use script in order to get access to function on serverside:

<script>
      $('#saveToFile').click(function(){
          //setTimeout($.get('/renewAfterDownload'), 5000);
          $.get('/renewAfterDownload')
      });
</script>

Here is my serverside code:

app.get('/renewAfterDownload', function (req, res){
  fs.writeFile('public/files/2pac.doc', '', function(){console.log('done')});
})

I have problem: it clears file exactly after i click to download it, so it saves empty file. I have trying to use setTimeout, but it doesn't help. How can I fix this?

Andy
  • 79
  • 7
  • Your logic is wrong! Content should be generated dynamically instead of being read from a file and then deleted. – mr mcwolf Jun 17 '22 at 10:40
  • Content is generated dynamically, I append it to file from MongoDB, where my content is saved, but i want to clear my file after I download it in order to save another content in my file and again repeat these steps: append to file my content, download file, clear file. If my logic is wrong, can you give a piece of advice, please? Or any example? @mrmcwolf – Andy Jun 17 '22 at 10:52
  • Roughly, make endpoint *app.get('./files/2pac.doc', function (req, res) {});* and use the *res* object to serve dynamically generated content (with the correct headers depending on the content you will be serving). You just need to physically turn off file references. – mr mcwolf Jun 17 '22 at 11:20
  • @mrmcwolf I don't understand your suggestion, can you show code example, please? – Andy Jun 17 '22 at 11:39
  • https://pastebin.com/hrLySUqh – mr mcwolf Jun 17 '22 at 11:53
  • @mrmcwolf thank you very much, I found a solution), but i can't rate you( – Andy Jun 17 '22 at 11:55

0 Answers0