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

标签 javascript node.js express fs

即使服务器上的文件包含“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

关于javascript - 为什么 Node fs.writeFile() 方法成功,但随后向浏览器发送了一个空文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34202420/

相关文章:

javascript - Json 差异补丁 Javascript - extjs

javascript - Express : No data received in final step 的链式 promise

javascript - 如何在动态加载的脚本中使用 jQuery on()

javascript - 如何在 SPA 应用程序中处理 "intention to open link in new page"?

javascript - JS RegExp 如何不允许特殊字符和数字?

javascript - 当我将图像上传到服务器nodejs时找不到文件(使用multer)

javascript - 同时运行 cURL 和 Node 服务器

javascript - Dust onLoad 上下文始终未定义

javascript - 带有明确 .set() 用途的 Node ?

javascript - Express:我可以在一个app.use中使用多个中间件吗?