无法流式传输到未链接的文件

时间:2019-01-24 15:10:49

标签: javascript node.js

我正在创建一个系统,该系统需要在短时间内缓存文件,然后将其删除。我遇到一个错误,如果我尝试删除后缓存相同的已删除文件,则会出现权限错误。

我已经复制了我的问题,看起来像这样:

//@ts-check
const fs = require("fs")
const promisify = require("util").promisify
const unlink = promisify(fs.unlink)

const SOURCE = "a.txt"
const DESTINATION = "b.txt"

function init() {
  console.info("Running operation")

  const sourceStream = fs.createReadStream(SOURCE)
  const destinationStream = fs.createWriteStream(DESTINATION)

  sourceStream.on("close", async () => {
    await unlink(DESTINATION)
    init()
  })

  sourceStream.pipe(destinationStream)
}

init()

运行时,这是记录到控制台的内容:

Running operation
Running operation
Running operation
events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: EPERM: operation not permitted, open 'D:\Projects\test\b.txt'
Emitted 'error' event at:
    at WriteStream.onerror (_stream_readable.js:690:12)
    at WriteStream.emit (events.js:182:13)
    at lazyFs.open (internal/fs/streams.js:273:12)
    at FSReqWrap.oncomplete (fs.js:141:20)

即使很奇怪,在抛出错误之前它可以运行相同操作的次数也有所不同。有时3点后会失败,有时5点后会失败。

那么这是怎么回事?

2 个答案:

答案 0 :(得分:1)

您需要等待destinationStream结束才能再次读取。尝试这样做:

 destinationStream.on("close", () => {
      await unlink(DESTINATION)
      init()
 })

答案 1 :(得分:-1)

如果我的问题正确,那么也许您应该寻找finish事件。

更改此:

const sourceStream = fs.createReadStream(SOURCE)
const destinationStream = fs.createWriteStream(DESTINATION)

sourceStream.on("close", async () => {
  await unlink(DESTINATION)
  init()
})

sourceStream.pipe(destinationStream)

对此:

const sourceStream = fs.createReadStream(SOURCE)
const destinationStream = fs.createWriteStream(DESTINATION)

sourceStream.pipe(destinationStream)
   .on('finish', async () => {
     await unlink(DESTINATION);
     console.log('Done');
     init()
   })