为什么Node fs.writeFile()方法成功,但是一个空文件然后被发送到浏览器?

下面的callback函数发送一个空文件给浏览器,即使该文件在服务器上包含'helloworld':

router.get('/Download', function(req, res) { var fs = require('fs') fs.writeFile('helloworld.txt', 'helloworld'); res.download('helloworld.txt'); }) 

writeFile是asynchronous的。 或者使用它作为:

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

或使用writeFileSync

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

试着找出你的代码是否有

process.exit()

因为某些原因。 如果你这样做,注释掉这一个,你会很好去。 我的版本是v8.6.0。

另请参阅: node – fs.writeFile创build一个空白文件