I want to print JSON.stringify()'d objects to the console, for context as part of a Mocha test suite output.
As the tests indent, I'd like the object log lines to be indented far enough rightwards (say, 3-4 tab spaces) that they are recognisably in the right describe() group.
How could I achieve this with something like console.log or process.stdout.write?
If just used for console.log you might want to look up for groups, check this on your console:
var obj = {
  a : 1,
  b : 2,
  c: 3
  }
console.log('Non-tabbed');
console.group();
console.log(JSON.stringify(obj, null, 2));
console.groupEnd();
console.log('Back to non-tabbed');
Works fine on current browsers and latest node. There's also a package on npm that might just work for that if you are working with older node versions.
node-console-group
This shifts the whole JSON string by 3 spaces. It breaks the JSON string by new lines, then adds on each line 3 spaces to a new string which will hold every line shifted.
var results = document.getElementById('results');
var obj = {
    a: 5,
    b: 3,
    c: 4
};
var string = JSON.stringify(obj, null, 2);
var stringShifted = '';
string.split('\n').forEach(function(line){
    stringShifted += '   ' + line + '\n';
});
console.log(string);
console.log(stringShifted);
results.innerHTML = 'Before : \n' + string;
results.innerHTML += '\n\nAfter : \n' + stringShifted;
<pre id="results"></pre>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With