Read buffer object in node.js

I am trying to get an html page through this node module called Wreck

Getting data is very easy, but I canโ€™t get it.

'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 is just an instance from the developer readme. according to the documentation, body should return a buffer object, but how can I read inside the body? I read to use toJSON or toString (), but I don't get any result

+5
source share
1 answer

... but I get no result

You get the result, an empty Buffer , but it does not want you to like it, perhaps.

The point is that you are using the read method incorrectly, passing it in a callback to the get method. The get , post , put and delete methods already call read internaly and return a readable Buffer for you in the callback. Take a look at get doc :

get (uri, [options], callback)

Convenient method for GET operations.

  • uri - URI of the requested resource.
  • options is an additional configuration object containing settings for query and read operations.
  • callback - callback function using the signature function (err, response, payload), where:
    • err is any error that may have occurred during request processing.
    • response is an HTTP Incoming Message object, which is also a readable stream.
    • payload - payload in the form of a buffer or (optionally) parsed JavaScript object (JSON).

Thus, using the get method is quite simple (using your own example):

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

Source: https://habr.com/ru/post/1201414/


All Articles