index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var MOVE_LEFT = new Buffer('1b5b3130303044', 'hex').toString();
  2. var MOVE_UP = new Buffer('1b5b3141', 'hex').toString();
  3. var CLEAR_LINE = new Buffer('1b5b304b', 'hex').toString();
  4. var stringWidth = require('string-width');
  5. module.exports = function(stream) {
  6. var write = stream.write;
  7. var str;
  8. stream.write = function(data) {
  9. if (str && data !== str) str = null;
  10. return write.apply(this, arguments);
  11. };
  12. if (stream === process.stderr || stream === process.stdout) {
  13. process.on('exit', function() {
  14. if (str !== null) stream.write('');
  15. });
  16. }
  17. var prevLineCount = 0;
  18. var log = function() {
  19. str = '';
  20. var nextStr = Array.prototype.join.call(arguments, ' ');
  21. // Clear screen
  22. for (var i=0; i<prevLineCount; i++) {
  23. str += MOVE_LEFT + CLEAR_LINE + (i < prevLineCount-1 ? MOVE_UP : '');
  24. }
  25. // Actual log output
  26. str += nextStr;
  27. stream.write(str);
  28. // How many lines to remove on next clear screen
  29. var prevLines = nextStr.split('\n');
  30. prevLineCount = 0;
  31. for (var i=0; i < prevLines.length; i++) {
  32. prevLineCount += Math.ceil(stringWidth(prevLines[i]) / stream.columns) || 1;
  33. }
  34. };
  35. log.clear = function() {
  36. stream.write('');
  37. };
  38. return log;
  39. };
  40. module.exports.stdout = module.exports(process.stdout);
  41. module.exports.stderr = module.exports(process.stderr);