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

SAN*_*les 2 javascript fs node.js express

以下回调函数将空文件发送到浏览器,即使该文件在服务器上包含"helloworld":

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

x_m*_*ras 5

writeFile是异步的.要么用它:

fs.writeFile('helloworld.txt', 'helloworld', function () {
    res.download('helloworld.txt');
});
Run Code Online (Sandbox Code Playgroud)

或使用 writeFileSync

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