Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indented, multi-line logging in NodeJS

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?

like image 632
yellow-saint Avatar asked Sep 12 '15 16:09

yellow-saint


1 Answers

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>
like image 195
MinusFour Avatar answered Oct 25 '22 01:10

MinusFour