29

I'm looking for an equivalent of var_dump in node.js.

I'd like to send the content of the request / response circular structure as a part of the response.

I know I can see it in the console, but that's not what I'm looking for.

4 Answers 4

44

To get what you’d get in the console by using console.log as a string for sending to the client as part of your response, you can use util.inspect.

"use strict";

const http = require("http");
const util = require("util");

http.createServer((request, response) => {
    response.setHeader("Content-Type", "text/plain;charset=utf-8");
    response.end(util.inspect(request));
}).listen(8000, "::1");
Sign up to request clarification or add additional context in comments.

1 Comment

For better formatted: console.log(util.inspect(request, { depth: null, colors: true, compact: true }));
6

You can simply use the NPM package var_dump

npm install var_dump --save-dev

Usage:

const var_dump = require('var_dump')
    
var variable = {
  'data': {
    'users': {
      'id': 12,
      'friends': [{
        'id': 1,
        'name': 'John Doe'
      }]
    }
  }
}
 
// print the variable using var_dump
var_dump(variable)

This will print:

object(1) {
    ["data"] => object(1) {
        ["users"] => object(2) {
            ["id"] => number(12)
            ["friends"] => array(1) {
                [0] => object(2) {
                    ["id"] => number(1)
                    ["name"] => string(8) "John Doe"
                }
            }
        }
    }
}

Link: https://www.npmjs.com/package/var_dump

Thank me later!

Comments

1

There is a npm package called circular-json, it's very good to use. I wonder why it is not built-in...

1 Comment

circular-json package has been deprecated. This package's author recommends to use flatted package: github.com/WebReflection/flatted#flatted
1

What about using JSON.stringify()?

console.log("Object:" + JSON.stringify(object));

1 Comment

For better formatted: console.log("Object:" + JSON.stringify(object, null, 2));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.