node.js - 自己的直通流不传输数据

标签 node.js stream

我目前正在学习 Node.js 流,因此我想编写自己的自定义流模块。这是我目前所拥有的:

index.js:

fs = require("fs")
var module = require("./module")
var ws = fs.createWriteStream("out.txt")

fs.createReadStream("in.txt")
  .pipe(module())
  .pipe(ws)

模块.js:

var Stream = require('stream').Stream;

module.exports = function() {
  var stream = new Stream();

  this.writable = true;
  this.readable = true;

  stream.write = function(data) {
    console.log("write")
    stream.emit("data", data)
  }

  stream.end = function() {
    console.log("end")
    stream.emit("end")
  }

  stream.destroy = function() {
    console.log("destroy")
    stream.emit("close")
  }

  return stream;
}

in.txt:

text
text
text
text
text
text
text
text
text
text

问题是 out.txt 为空,并且 stream.write 函数从未被调用。为什么会这样?如果我注释掉我的中间管道就一切正常!

最佳答案

您的代码中有一个可以轻松修复的错误。

module.js中更改:

this.writable = true;
this.readable = true;

至:

stream.writable = true;
stream.readable = true;

它会起作用。

此外,如果您想了解有关如何使用流的更多信息,子堆栈以 stream handbook 的形式创建了一个很好的资源。 .

关于node.js - 自己的直通流不传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12623124/

相关文章:

javascript - 抓取: Get Link that is only visible on the website not in the html

javascript - Node.js : SocketIO vs http request performance

java - Chunkwise-将数据从InputStream复制到OutputStream + 在末尾获取byte[]

node.js - 如何在不使用阻塞 stdio 的情况下从 node.js 中的子进程传输/流式传输大数据?

javascript - 如何处理 Net Core 中的 net::ERR_INTERNET_DISCONNECTED 错误

javascript - 如何让一个简单的 localstack/localstack 与 node.js 一起工作

node.js - 使用 Node 从图形 api 获取数据

javascript - 切换到 Windows 后出现 node.js 错误 - 错误 : %1 is not a valid Win32 application

c++ - 从另一个文件读取时写入文件

java - 卡夫卡流: how to handle dynamic conditions in a filter?