无法删除读取流使用的文件

时间:2018-03-21 08:25:14

标签: javascript node.js express

我正在尝试在POST请求后删除文件夹,但我不能,因为它正在被读取流使用。我尝试了.destroy();.unpipe();,但它仍在使用中。

我全局声明我的读取流变量,所以我可以销毁它并将其从作用域中取消。

var file;

这是我的读取流功能:

app.get('/api/video/:folder' , function(req, res) {
  var streamer = req.params.folder
  const path = 'D:/Clips/' + folder + '/clip.mp4'
  const stat = fs.statSync(path)
  const fileSize = stat.size
  const range = req.headers.range

  if (range) {
    const parts = range.replace(/bytes=/, "").split("-")
    const start = parseInt(parts[0], 10)
    const end = parts[1]
      ? parseInt(parts[1], 10)
      : fileSize-1

    const chunksize = (end-start)+1
    //const file = fs.createReadStream(path, {start, end})
    file = fs.createReadStream(path, {start, end})
    const head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    }

    res.writeHead(206, head)
    file.pipe(res)
  } else {
    const head = {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    }
    res.writeHead(200, head)
    fs.createReadStream(path).pipe(res)
  }
});

这是我的删除请求:

app.post('/api/delete', urlencodedParser, function(req,res){
  file.unpipe();
  file.destroy();
  var delFolder = req.body.folder;
  fsextra.removeSync('D:/Clips/' + delFolder);
});

它给了我错误,因为读取流正在使用该文件。

我如何结束阅读流程?

0 个答案:

没有答案
相关问题