Printing a buffer object

In different troubleshooting contexts, printing the contents of a buffer object might result in decimal, hex, or ASCII output.

When you troubleshoot a GatewayScript file, there are several ways to output a buffer object. You can print the contents of the buffer to the system log file, or you can print the buffer object while debugging. The toString() API can modify the behavior of printing an object.
  • console.log(buf);
  • print buf;
  • print buf.toString();

The console.log() API writes a log message to the DataPower® system log. The type of the argument determines how the output is represented in the system log. For a buffer object, the output content is a formatted hex string.

In the debugger, the print command prints the object properties with the value. When the argument is a buffer object, the output shows the data array and length. If the JSON.stringify() API is applied to the buffer object, the function returns the serialized buffer object in a JSON string.

If you want to print the buffer object in ASCII string, the toString() API returns a string from the buffer data.

In the following example, the buffer is populated with the ASCII string test and manipulated with JSON.stringify() and JSON.parse() APIs.
function myFunction()
{
  console.info("Testing myFunction");

  var buf = new Buffer('test');
  var jsonstr = JSON.stringify(buf);
  var copy = JSON.parse(jsonstr, function(key, value) {
    return value && value.type === 'Buffer'
      ? new Buffer(value.data)
      : value;
  });
  console.log(copy);
  debugger;
}
This example shows the output that the console.log(); statement prints to the log.
  • The console.log(copy); statement output is the log message in hex.
    <Buffer 74 65 73 74>
The following examples show the output that prints when the debugger print commands are run when processing stops at the debugger; statement.
  • The print copy command in the debugger outputs decimal data values and the array length.
    (debug) print copy
    { '0': 116, '1': 101, '2': 115, '3': 116, length: 4 }
  • The print jsonstr command in the debugger outputs the JSON string of the serialized buffer object.
    (debug) print jsonstr
    {"type":"Buffer", "data":[116,101,115,116]}
  • The print copy.toString() command in the debugger outputs the ASCII text string.
    (debug) print copy.toString()
    test