Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read buffer object in node.js

I'm trying to get html page through this node module called Wreck

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? I have read to use toJSON or toString() but I don't get any result

like image 531
Mazzy Avatar asked Aug 29 '14 12:08

Mazzy


People also ask

How parse buffer to string in node JS?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.


1 Answers

...but I don't get any result

You ARE getting a result, an empty Buffer, but it's not want you want, probably.

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

get(uri, [options], callback)

Convenience method for GET operations.

  • uri - The URI of the requested resource.
  • options - Optional config object containing settings for both request and read operations.
  • callback - The callback function using the signature function (err, response, payload) where:
    • err - Any error that may have occurred during handling of the request.
    • response - The HTTP Incoming Message object, which is also a readable stream.
    • payload - The payload in the form of a Buffer or (optionally) parsed JavaScript object (JSON).

So, the use of the get method is pretty straightforward (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);
like image 192
Rodrigo Medeiros Avatar answered Sep 29 '22 15:09

Rodrigo Medeiros