简体   繁体   English

如何将此参数传递给侦听器?

[英]How is this parameter being passed to the listener?

use strict;

var fs = require('fs);

var readable = fs.createReadStream(__dirname + '/greet.txt', {encoding: 'utf8', highwaterMark: 32 * 1024 });

readable.on('data', function(chunk) {
  console.log(chunk.length)
});

If I understand correctly, in node, the readable stream inherits from EventEmitter, which allows it to make use of the listener / .on method. 如果我正确理解,则在节点中,可读流继承自EventEmitter,这使它可以利用listener / .on方法。

But, how does the callback : , function(chunk){ console.log(chunk.length)} know the value of the chunk parameter? 但是,callback:,function(chunk){console.log(chunk.length)}如何知道chunk参数的值?

EventEmitter instance has a method called "emit", so somewhere inside the fs readstream, it is called like this EventEmitter实例具有一个称为“ emit”的方法,因此在fs readstream内部的某个地方,它的调用方式如下:

emitter.emit('data', chunk);

https://nodejs.org/api/events.html#events_passing_arguments_and_this_to_listeners https://nodejs.org/api/events.html#events_passing_arguments_and_this_to_listeners

Answering to your comment, no, the listener doesn't detect or call anything. 回答您的评论,不,侦听器不会检测到或呼叫任何东西。 It's the other way around, fs.createReadStream() is an event emitter. 与此相反, fs.createReadStream()是事件发射器。 readable.on('data', function() { ... }) means "readable, please call this function when you emit 'data' event". readable.on('data', function() { ... })意思是“可读,请在发出'data'事件时调用此函数”。 readable emits data events when it has data to "give", calls all registered listeners (only function(chunk) in your example) and provides the parameters like detailed in the doc. 当有数据要“给” 可读发出数据的事件,呼吁所有注册的侦听器(仅function(chunk)在你的例子),并提供像DOC详细的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM