Search code examples
node.jsread-eval-print-loopstringify

How does the node.js REPL stringify output?


How does the node.js REPL stringify the objects that it prints? I became curious after running into this oddity with an array containing a key-value pair (?!):

> var arr = [1]
undefined
> arr
[ 1 ]
> arr.key = "value"
'value'
> arr
[ 1, key: 'value' ]

The typical functions don't appear to be generating exactly [ 1, key: 'value' ].

> arr.toString()
'1'
> JSON.stringify(arr)
'[1]'
> require("util").inspect(arr, {showHidden: true})
'[ 1, [length]: 1, key: \'value\' ]'

The last one's almost it, but has an additional [length] (to clarify, the quotes obviously don't matter). I'm running node v0.10.33.


Solution

  • You're almost there; util.inspect returns a string and is called without showHidden:

    > require("util").inspect(arr)
    '[ 1, key: \'value\' ]'
    > console.log( require("util").inspect(arr) )
    [ 1, key: 'value' ]
    

    If you log a string to the console, it'll be wrapped in quotes, but console.log does not do this. Write inspect's output to a file if you want to verify that it's exactly the same as console.log's output:

    > require("fs").writeFileSync("dump.txt", require("util").inspect(arr));
    

    In your console:

    $ cat dump.txt
    [ 1, key: 'value' ]
    

    Regarding the first paragraph:

    array containing a key-value pair (?!):

    It's not that weird - arrays are objects, so it's perfectly valid. But it might be confusing to other people looking at your code. :-)

    Doing that is not much different from this:

    var fn = function() {}
    fn.key = "value";
    

    It'll look just like your array example if you were to log this.