【问题标题】:Resume flow after write stream emits an error?写入流发出错误后恢复流?
【发布时间】:2014-06-15 16:26:57
【问题描述】:

我使用 nodejs 流作为数据处理的管道。我遇到的问题是,一旦我的 writeStream 目标发出错误,管道就会停止将数据流向 writeStream。事实上,看起来pipe 就是这样实现的。一旦发出一个错误,writeStream 就会从管道中分离出来。 https://github.com/joyent/node/blob/master/lib/stream.js#L89-112

这对于我想要的东西来说似乎有点激进。我希望能够记下错误,但要保持管道运行。我该怎么做?

我的直播如下所示:

client.readStream()
        .pipe(process1)
        .pipe(process2)
        .pipe(process3)
        .pipe(mongo.writeStream())
        .on('data', console.log)
        .on('error', console.log);

process1process2process3 被实现为事件流库中的 .map()。

mongo 写入流如下所示。

function MongoStream(_mongo) {
  Stream.Writable.call(this, { objectMode : true });
}

util.inherits(MongoStream, Stream.Writable);

MongoStream.prototype._write = function (model, encoding, callback) {
  var self = this;
  console.log("Saving model");
  model.save(function(err, result) {
    if(err){ 
        self.emit('error', err);
    } else {
        console.log("model saved");
        self.emit('data', result);
    }
    callback();
  });
};

读取流只是来自猫鼬模型的.find().stream()

【问题讨论】:

    标签: node.js


    【解决方案1】:

    为事件使用除error 之外的名称:

    self.emit('error', err);
    

    可以说:

    self.emit('err', err);
    

    这不会触发 .pipe 安装的侦听器。

    然后使用:.on('err', console.log)

    这可能比尝试更改.pipe 以使其对error 没有任何作用要好。

    【讨论】:

    • 啊,是的。我考虑过这一点,但我仍然否认这是一般处理错误的方式。我认为这是最好的解决方案。谢谢!
    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2020-12-02
    相关资源
    最近更新 更多