简体   繁体   English

在node.js中读取缓冲区对象

[英]Read buffer object in node.js

I'm trying to get html page through this node module called Wreck 我正试图通过名为Wreck的节点模块获取html页面

It should be very easy to get data but I'm unable to get them 获取数据应该很容易,但我无法得到它们

'use strict';

var Wreck = require('wreck');

var url = 'http://www.google.it';

var callback = function(err, response, payload){
  Wreck.read(response, null, function(err, body){
      //here print out the html page
  });
};

Wreck.get(url, callback);

Here above a simple script just a copy from the readme of the developer. 上面是一个简单的脚本,只是开发人员自述文件的副本。 according to the documentation body should return a buffer object but how can I read inside a body object? 根据文档body应该返回一个缓冲对象但是如何读取一个body对象? I have read to use toJSON or toString() but I don't get any result 我已阅读使用toJSON或toString()但我没有得到任何结果

...but I don't get any result ......但我没有得到任何结果

You ARE getting a result, an empty Buffer , but it's not want you want, probably. 你得到一个结果,一个空的Buffer ,但它可能不是你想要的。

The fact is: you are using the read method wrong, passing it inside a callback to the get method. 事实是:您使用的read方法错误,将其传递给get方法的回调。 The methods get , post , put and delete already call read internaly and return the readable Buffer for you, in a callback. getpostputdelete已经调用read internaly并在回调中为您返回可读Buffer Take a look at the get doc : 看一下get doc

get(uri, [options], callback) get(uri,[options],callback)

Convenience method for GET operations. GET操作的便捷方法。

  • uri - The URI of the requested resource. uri - 请求的资源的URI。
  • options - Optional config object containing settings for both request and read operations. options - 包含请求和读取操作设置的可选配置对象。
  • callback - The callback function using the signature function (err, response, payload) where: callback - 使用签名函数(错误,响应,有效负载)的回调函数,其中:
    • err - Any error that may have occurred during handling of the request. 错误 - 处理请求期间可能发生的任何错误。
    • response - The HTTP Incoming Message object, which is also a readable stream. response - HTTP Incoming Message对象,也是可读流。
    • payload - The payload in the form of a Buffer or (optionally) parsed JavaScript object (JSON). payload - 以Buffer或(可选)解析的JavaScript对象(JSON)形式的有效负载。

So, the use of the get method is pretty straightforward (using your own example): 因此,使用get方法非常简单(使用您自己的示例):

var callback = function(err, response, payload){
  console.log(payload.toString()); // converting the buffer to a string and logging
};

Wreck.get(url, callback);

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

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