【问题标题】:Delete file after using response.download() in node.js?在 node.js 中使用 response.download() 后删除文件?
【发布时间】:2020-05-02 21:34:39
【问题描述】:

我正在开发一个应用程序,该应用程序有一个使用response.download() 将文件下载到客户端设备的服务器。 (我使用的是 node.js、express 和 fs)一旦下载了这些文件,它们只是占用空间,所以我尝试在下载后调用 fs.unlinksync 以摆脱它们。但是没有这样的运气:我只是收到以下错误:NOENT: No such file or directory.

这里是相关的服务器端代码:

app.get("/file", function(request, response) {
  var filename = request.query.f;
  var filePath = "public/" + filename
  response.download(filePath);
//this is where I've tried putting fs.unlink
});

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: node.js express server download fs


    【解决方案1】:

    response.download有回调函数,下载后可以删除文件

    response.download(filePath, yourFileName, function(err) {
      if (err) {
        console.log(err); // Check error if you want
      }
      fs.unlink(yourFilePath, function(){
          console.log("File was deleted") // Callback
      });
    
      // fs.unlinkSync(yourFilePath) // If you don't need callback
    });
    

    【讨论】:

    • 我试过了,得到了TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
    • 它不会删除给定路径中的文件。
    • 这在基于 Chromium 的移动浏览器中不起作用,因为用户会收到下载选项的提示。
    【解决方案2】:

    res.download() 是异步的。这意味着它开始操作然后返回,因此如果您尝试在下一行删除文件,下载操作将尚未完成。 res.download() 有一个可选的回调,它会在操作完成时告诉您,您可以在该回调中删除文件。

    app.get("/file", function(request, response) {
      var filename = request.query.f;
      var filePath = "public/" + filename
      response.download(filePath, {dotfiles: "deny"}, function(err) {
         // the operation is done here          
      });
    });
    

    【讨论】:

    • @s.j - 这个问题或答案与删除文件有什么关系?如果您对删除有任何疑问,请提出您自己的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 2022-12-12
    • 2011-07-15
    • 1970-01-01
    • 2019-09-10
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多