Node.js stream-adventure duplexer_redux

时间:2014-06-10 00:11:13

标签: javascript node.js stream

这是来自substack的流冒险问题集的问题。问题和解决方案的链接在这里:

https://github.com/substack/stream-adventure/tree/master/problems/duplexer_redux

我不明白"写"方法可以在解决方案中正常工作:

function write (row) {
    counts[row.country] = (counts[row.country] || 0) + 1;
}

具体来说,是否有任何保证" row"将如下全记录? " row"是否可行?可能是部分记录吗?

{"短":" OH""名称":"俄亥俄州""国家":& #34; US"}

1 个答案:

答案 0 :(得分:0)

仔细查看代码,duplexer似乎设置stream.write来调用输入write上的writer函数(在此示例中为through实例)。因此,当duplexer.write被调用时,它会调用它writer.writehttps://github.com/Raynos/duplexer/blob/6d6f4b5b85964f7037917a9a3b70659c6e152f21/index.js#L44-L48

function proxyWriter(methodName) {
    stream[methodName] = method

    function method() {
        return writer[methodName].apply(writer, arguments)
    }
}

through内,如果提供了write变量write,则使用输入write = write || function (data) { this.queue(data) } https://github.com/dominictarr/through/blob/6f814a601b37db1f44113e56a1eaa0c32a33b0a2/index.js#L14

stream.write

当调用自己的stream函数时(through会返回write),它会调用stream.write = function (data) { write.call(this, data) return !stream.paused } 代替: https://github.com/dominictarr/through/blob/6f814a601b37db1f44113e56a1eaa0c32a33b0a2/index.js#L25-L28

write

所有这一切都说,在duplexer上调用write时,它看起来好像是调用你定义的{{1}}函数传递它收到的参数。所以你每次都应该收到整个论点。

希望有道理吗?