为什么Node fs.writeFile()方法成功,但随后会向浏览器发送一个空文件

Why is Node fs.writeFile() method successful, but an empty file is then sent to the browser?

本文关键字:浏览器 一个 文件 writeFile fs Node 方法 成功 为什么      更新时间:2023-09-26

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

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

writeFile是异步的。或者将其用作:

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创建一个空白文件

相关文章: