3

The following callback function sends an empty file to the browser even though the file contains 'helloworld' on the server:

router.get('/Download', function(req, res) {
    var fs = require('fs')
    fs.writeFile('helloworld.txt', 'helloworld');
    res.download('helloworld.txt');
})
SANBI samples
  • 2,058
  • 2
  • 14
  • 20
  • Programming with Node.JS is asynchronous programming. You should get use with that, if you want to get the maximum of Node.js. – Rolice Dec 10 '15 at 13:02

2 Answers2

7

writeFile is asynchronous. either use it as:

fs.writeFile('helloworld.txt', 'helloworld', function () {
    res.download('helloworld.txt');
});

or use writeFileSync

https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

x_maras
  • 2,177
  • 1
  • 25
  • 34
  • can you please explain why isn't asynchronous method is working? – Alex Jones Jul 07 '18 at 11:12
  • Long story short `writeFile` might take a while to execute in completion. `res.download` will execute before the writeFile is completed. At the moment it executes the file is empty. It is due to a javascript (nodejs) construct the event loop. You can read about it in the 2 following links and I recommend to look for more source based on how you learn better, e.g. youtube videos, interactive learning, etc. https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#header-setimmediate-vs-settimeout & https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Event_loop – x_maras Jul 08 '18 at 18:41
0

Try to find out if your code has

process.exit()

for some reason. If you do, comment out this one and you will be good to go. My version is v8.6.0.

See also: node - fs.writeFile creates a blank file

Ibio Tan
  • 111
  • 3
  • 8