Timothy C. Quinn
Timothy C. Quinn

Reputation: 4515

Equivalent of `util.inspect` in Deno

Does Deno have a utility function that dumps a Object or primitive to a string like Node.js util.inspect?

For example in Node.js I create an json object and want to dump out its contents in Node:

> m = {k1:'v1', k2:'v2'}
{ k1: 'v1', k2: 'v2' }
> util.inspect(m)
'{ k1: \'v1\', k2: \'v2\' }'

Upvotes: 10

Views: 1419

Answers (3)

Lukalot
Lukalot

Reputation: 41

Additionally, if you want to override to return your own results from Deno.inspect, you can add a Deno.customInspect method to your classes like so:

class someClass {
    // code ...

    [Symbol.for("Deno.customInspect")]() {
        return 'any ol string';
    }

}

Here's the documentation for Deno.inspect and Deno.customInspect

Upvotes: 4

aef
aef

Reputation: 4708

Generally use Deno.inspect(someObject).

In case you want to customize the string representation of Deno.inspect for a specific class, since Deno 1.19, you are supposed to implement something like the following:

class MyClass {

  // …

  [Symbol.for("Deno.customInspect")]() {
    return "custom string representation;
  }

  // …
}

Objects displayed using console.log(someObject) will also be affected by this.

Documentation can be found here.

Note that the version shown by @Lukalot is deprecated since Deno 1.19 and might therefore stop to work in future versions.

Upvotes: 3

Timothy C. Quinn
Timothy C. Quinn

Reputation: 4515

Deno's equivalent of Node's util.inspect is Deno.inspect.

For example in the deno REPL:

> m = {k1:'v1', k2:'v2'}
{ k1: "v1", k2: "v2" }
> Deno.inspect(m)
{ k1: "v1", k2: "v2" }

Upvotes: 14

Related Questions