【问题标题】:How to split WriteStream while writing to it?如何在写入时拆分 WriteStream?
【发布时间】:2019-09-11 02:00:51
【问题描述】:

问题:

我有fs.createWriteStream(filename),其中文件名是通过res.pipe(); 写入的mp3 文件。来自远程服务器的响应是永无止境的音频数据流

服务器定时发送res.on('metadata'),可以解析,我们知道歌曲结束,新歌开始。那时我必须“拆分”“文件名”并开始写另一个“文件名2”,这最终是另一首歌曲。

问题是,我无法关闭“filename1”的流,并启动另一个fs.createWriteStream(filename2),因为它正被“res.pipe()”使用,如果它已关闭,则管道中断 -> 节点会抛出错误我无法写入已关闭的流 -> 资源中断 -> 连接丢失,我必须手动重新启动应用程序...

应该如何正确完成?

谢谢!

【问题讨论】:

  • 您需要考虑不使用res.pipe(),因为您需要更好地控制目标流。

标签: javascript node.js


【解决方案1】:

您需要介于 fs 写入流和响应流之间的内容。例如,您可以创建自己的 Writable,这是一个粗略的示例,您仍然可以 res.pipe() 到,当您想更改文件时,您可以调用 writable.changeFile()

const { Writable } = require("stream");

class MyWritable extends Writable {
  constructor(options) {
    super(options);

    this.doChangeFile = false;
    this.stream = null;
  }

  _write(chunk, encoding, callback) {
    if (!this.stream) {
      // No stream, start a new one
      const filename = "generate a new filename here";

      this.stream = fs.createWriteStream(filename);
    }

    if (this.doChangeFile) {
      // Swapping files, end current stream and return
      this.stream.end(chunk, encoding, callback);
      this.stream = null;

      this.doChangeFile = false;
      return;
    }

    // Otherwise write chunks to current stream
    this.stream.write(chunk, encoding, callback);
  }

  changeFile() {
    this.doChangeFile = true;
  }
}

const writable = new MyWritable();

【讨论】:

  • 感谢您的回答,将深入探讨!
猜你喜欢
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多