Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions benchmark/util/strip-vt-control-characters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const common = require('../common.js');

const { stripVTControlCharacters } = require('node:util');
const assert = require('node:assert');

const bench = common.createBenchmark(main, {
input: ['noAnsi-short', 'noAnsi-long', 'ansi-short', 'ansi-long'],
n: [1e6],
});

function main({ input, n }) {
let str;
switch (input) {
case 'noAnsi-short':
str = 'This is a plain text string without any ANSI codes';
break;
case 'noAnsi-long':
str = 'Long plain text without ANSI. '.repeat(333);
break;
case 'ansi-short':
str = '\u001B[31mHello\u001B[39m';
break;
case 'ansi-long':
str = ('\u001B[31m' + 'colored text '.repeat(10) + '\u001B[39m').repeat(10);
break;
}

bench.start();
for (let i = 0; i < n; i++) {
const result = stripVTControlCharacters(str);
assert.ok(typeof result === 'string');
}
bench.end(n);
}
4 changes: 4 additions & 0 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -3036,6 +3036,10 @@ if (internalBinding('config').hasIntl) {
function stripVTControlCharacters(str) {
validateString(str, 'str');

if (!StringPrototypeIncludes(str, '\u001B') &&
!StringPrototypeIncludes(str, '\u009B'))
return str;

return RegExpPrototypeSymbolReplace(ansi, str, '');
}

Expand Down
10 changes: 10 additions & 0 deletions test/parallel/test-util.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,13 @@ assert.throws(() => {
message: 'The "str" argument must be of type string.' +
common.invalidArgTypeHelper({})
});

// stripVTControlCharacters: fast path returns input when no ANSI codes
assert.strictEqual(util.stripVTControlCharacters('hello'), 'hello');
assert.strictEqual(util.stripVTControlCharacters(''), '');

// stripVTControlCharacters: strips 7-bit ESC sequences
assert.strictEqual(util.stripVTControlCharacters('\u001B[31mfoo\u001B[39m'), 'foo');

// stripVTControlCharacters: strips 8-bit CSI sequences
assert.strictEqual(util.stripVTControlCharacters('\u009B31mfoo\u009B39m'), 'foo');
Loading