javascript - 在node.js中通过http.ClientRequest实现接口(interface)是什么意思?

标签 javascript node.js

我正在阅读the documentation for http.ClientRequest它说...“请求实现了 Writable Stream 接口(interface)。这是一个 EventEmitter。”这是什么意思?这是否意味着 http.ClientRequest 获取了 Writable Stream 和 EventEmitter 获取的所有方法和事件,并且它将接受的参数与 EventEmitter(事件,监听器)相同?

如果这是正确的,那么 example code for http.request 中怎么会这样呢? ...在 http.request 的回调函数中,有一行写着 res.on('data', ...)?文档说这个 res 参数实现了 http.ClientRequest,但是当我检查时,列出了stream.Readable 的“data”事件,但没有列出stream.Writable。

以下是来自 url 的示例代码:

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

最佳答案

根据http://nodejs.org/api/stream.html#stream_stream,第一个答案是肯定的。 , 所有流都是 EventEmitter 的实例。

关于第二个问题,

The documentation says that this res parameter implements http.ClientRequest,

不。返回的对象(即req)是实现可写流的ClientRequest实例,在示例代码中,data事件绑定(bind)到可读流的resdoc说:

http.request() returns an instance of the http.ClientRequest class. 

不要将请求响应混淆。 :)

关于javascript - 在node.js中通过http.ClientRequest实现接口(interface)是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21101623/

相关文章:

javascript - 如何在使用公共(public)文件夹的 Webhost 上组织 Angular 2 文件?

javascript - 在 Angular Material Accordion 中打开第一个附加的扩展面板

Javascript setInterval 不更新内部使用的时间戳

javascript - HTML5 Canvas 碰撞检测

javascript - IHttpPromise 使用 TypeScript 2.5 错误地扩展了 IPromise

mysql - 如何在 Waterline sails.js 中使用其同事的属性查找实体?

javascript - 使用express-expose和Handlebars.js给了我意外的 token &

Mysql, Node ,查询中的查询,如何从另一个查询填充映射函数中的属性

node.js - NodeJS 数据吞吐量

javascript - 在 Express 应用程序中使用 Nunjucks