Skip to content

Commit 1f55704

Browse files
kustoszbnoordhuis
authored andcommitted
util: fix util.inspect() line width calculation
Have the formatter filter out vt100 color codes when calculating the line width. Stops it from unnecessarily splitting strings over multiple lines. Fixes #5039.
1 parent 8548920 commit 1f55704

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

lib/util.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,7 @@ function reduceToSingleString(output, base, braces) {
418418
var length = output.reduce(function(prev, cur) {
419419
numLinesEst++;
420420
if (cur.indexOf('\n') >= 0) numLinesEst++;
421-
return prev + cur.length + 1;
421+
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
422422
}, 0);
423423

424424
if (length > 60) {

test/simple/test-util-inspect.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,31 @@ assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1
160160
subject.inspect = function() { return { foo: 'bar' }; };
161161

162162
assert.equal(util.inspect(subject), '{ foo: \'bar\' }');
163+
164+
// util.inspect with "colors" option should produce as many lines as without it
165+
function test_lines(input) {
166+
var count_lines = function(str) {
167+
return (str.match(/\n/g) || []).length;
168+
}
169+
170+
var without_color = util.inspect(input);
171+
var with_color = util.inspect(input, {colors: true});
172+
assert.equal(count_lines(without_color), count_lines(with_color));
173+
}
174+
175+
test_lines([1, 2, 3, 4, 5, 6, 7]);
176+
test_lines(function() {
177+
var big_array = [];
178+
for (var i = 0; i < 100; i++) {
179+
big_array.push(i);
180+
}
181+
return big_array;
182+
}());
183+
test_lines({foo: 'bar', baz: 35, b: {a: 35}});
184+
test_lines({
185+
foo: 'bar',
186+
baz: 35,
187+
b: {a: 35},
188+
very_long_key: 'very_long_value',
189+
even_longer_key: ['with even longer value in array']
190+
});

0 commit comments

Comments
 (0)