Skip to content

Inconsistent behavior between util.formatWithOptions and util.inspect #29726

Description

@tiagonapoli

The following snippet shows a possible unexpected output for formatWithOptions. On console.log(util.formatWithOptions({ }, '%s', obj)) I expected a output { a: [ '123' ] }, but got { a: [Array] } :

const util = require('util')

const obj = { a: ['123'] }

/************ formatWithOptions ************/

// { a: [Array] }
console.log(util.formatWithOptions({ }, '%s', obj))

// { a: [ '123' ] } - Note: this is not respecting the api docs, the first argument has to be an object
console.log(util.formatWithOptions('%s', obj))

/******************************************/

/************ inspect ************/

// { a: [ '123' ] }
console.log(util.inspect(obj, { }))

// { a: [ '123' ] }
console.log(util.inspect(obj))

/*******************************/

Since util.formatWithOptions('%s', obj) doesn't respect the api docs, maybe this is an expected behavior for util.formatWithOptions, in this case maybe it could be changed to have similar behavior to inspect?

Activity

  1. changed the title [-]Unexpected output with util.formatWithOptions[/-] [+]Inconsistent behavior between util.formatWithOptions and util.inspect[/+] on Sep 26, 2019
  2. tiagonapoli commented on Sep 26, 2019

    @tiagonapoli
    Author

    Saw that the following code specifies that the depth for %s is garanteed to be 0, overriding the given inspectOptions, is this the behavior intended?

    tempStr = inspect(tempArg, {
    ...inspectOptions,
    compact: 3,
    colors: false,
    depth: 0
    });

  3. BridgeAR commented on Sep 26, 2019

    @BridgeAR
    Member

    @tiagonapoli yes, that is intentional. The reason is that inspecting objects with %s was until recently not inspected at all but String(obj) was used and that would result in e.g. [object Object] for input like { a: true }.

    If you want to pass through objects, please use the %O formatter. That way the depth is handled as with util.inspect().

  4. added
    questionIssues asking questions about Node.js.
    utilIssues and PRs related to the built-in util module.
    on Sep 26, 2019
  5. BridgeAR commented on Sep 26, 2019

    @BridgeAR
    Member

    And util.formatWithOptions('%s', obj) should actually throw an error. You pass through '%s' as options.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionIssues asking questions about Node.js.utilIssues and PRs related to the built-in util module.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions