Equivalent of `util.inspect` in Deno
Asked Answered
D

3

10

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\' }'
Dick answered 11/5, 2020 at 3:49 Comment(0)
D
13

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" }
Dick answered 11/5, 2020 at 3:49 Comment(0)
T
4

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

Thacher answered 20/1, 2021 at 1:7 Comment(2)
That is slick! Thanks for sharing.Dick
This has been deprecated since Deno 1.19. See my answer for a more up-to-date solution.Coign
C
2

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.

Coign answered 20/4, 2022 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.