Skip to content

Instantly share code, notes, and snippets.

@papandreou
Last active August 16, 2016 23:13
Show Gist options
  • Save papandreou/00665390d3d91f805573ecd25a224b3d to your computer and use it in GitHub Desktop.
Save papandreou/00665390d3d91f805573ecd25a224b3d to your computer and use it in GitHub Desktop.
Count ansi colors with node.js
var fs = require('fs');
function awaitEcho() {
var buf = new Buffer(100);
var numRead;
var offset = 0;
var startTime = Date.now();
do {
if (offset >= buf.length) {
var reallocBuffer = new Buffer(2 * buf.length);
buf.copy(reallocBuffer);
buf = reallocBuffer;
}
try {
numRead = fs.readSync(0, buf, offset, 1);
offset += numRead;
} catch (e) {
if (e.code !== 'EAGAIN') {
throw e;
}
}
} while (buf.lastIndexOf(0x07, offset) === -1 && Date.now() - 100 <= startTime);
return buf.slice(0, offset);
}
var preamble = new Buffer([0x1b, 0x5d, 0x34, 0x3b]);
var postamble = new Buffer([0x3b, 0x3f, 0x07]);
function supportsColorNumber(tty, num) {
var e = Buffer.concat([preamble, new Buffer(String(num)), postamble]);
tty.write(e, 0, e.length);
var reply = awaitEcho();
return reply.length <= 1;
}
if (process.stdin.isTTY) {
process.stdout.setNoDelay(true);
process.stdin.setNoDelay(true);
var stdinWasRaw = process.stdin.isRaw;
process.stdin.setRawMode(true);
var rawStdout = new fs.SyncWriteStream(1, { autoClose: false });
// Binary search
var min = 0;
var max = 256;
var i;
while (min + 1 < max) {
i = Math.round((min + max) / 2);
if (supportsColorNumber(rawStdout, i)) {
max = i;
} else {
min = i;
}
}
console.log('Number of colors supported', max);
if (!stdinWasRaw) {
process.stdin.setRawMode(false);
}
process.stdin.setNoDelay(false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment