Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
util: fix util.inspect() line width calculation
Browse files Browse the repository at this point in the history
Have the formatter filter out vt100 color codes when calculating the
line width. Stops it from unnecessarily splitting strings over multiple
lines.

Fixes #5039.
  • Loading branch information
kustosz authored and bnoordhuis committed Mar 28, 2013
1 parent 8548920 commit 1f55704
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/util.js
Expand Up @@ -418,7 +418,7 @@ function reduceToSingleString(output, base, braces) {
var length = output.reduce(function(prev, cur) { var length = output.reduce(function(prev, cur) {
numLinesEst++; numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.length + 1; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0); }, 0);


if (length > 60) { if (length > 60) {
Expand Down
28 changes: 28 additions & 0 deletions test/simple/test-util-inspect.js
Expand Up @@ -160,3 +160,31 @@ assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1
subject.inspect = function() { return { foo: 'bar' }; }; subject.inspect = function() { return { foo: 'bar' }; };


assert.equal(util.inspect(subject), '{ foo: \'bar\' }'); assert.equal(util.inspect(subject), '{ foo: \'bar\' }');

// util.inspect with "colors" option should produce as many lines as without it
function test_lines(input) {
var count_lines = function(str) {
return (str.match(/\n/g) || []).length;
}

var without_color = util.inspect(input);
var with_color = util.inspect(input, {colors: true});
assert.equal(count_lines(without_color), count_lines(with_color));
}

test_lines([1, 2, 3, 4, 5, 6, 7]);
test_lines(function() {
var big_array = [];
for (var i = 0; i < 100; i++) {
big_array.push(i);
}
return big_array;
}());
test_lines({foo: 'bar', baz: 35, b: {a: 35}});
test_lines({
foo: 'bar',
baz: 35,
b: {a: 35},
very_long_key: 'very_long_value',
even_longer_key: ['with even longer value in array']
});

0 comments on commit 1f55704

Please sign in to comment.