log_table.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. var Table = require('cli-table');
  2. module.exports = exports = function logTable(data){
  3. if(typeof data !== 'object' || data === null){
  4. console.log('');
  5. return;
  6. }
  7. if(typeof data[Object.keys(data)[0]] !== 'object' || data[Object.keys(data)[0]] === null){
  8. console.log('');
  9. return;
  10. }
  11. var firstKey = Object.keys(data)[0];
  12. var firstObject = data[firstKey];
  13. var thead = Object.keys(firstObject);
  14. thead.unshift('(index)');
  15. var colWidths = thead.map(calculateColWidth);
  16. Object.keys(data).forEach(function(rowKey){
  17. var row = data[rowKey];
  18. if(typeof row == 'object'){
  19. Object.keys(row).forEach(function(k,i){
  20. var width = calculateColWidth (row[k]);
  21. if(colWidths[i+1] < width)
  22. colWidths[i+1] = width;
  23. });
  24. }
  25. });
  26. var table = new Table({
  27. head: thead,
  28. colWidths: colWidths
  29. });
  30. Object.keys(data).forEach(function(rowKey){
  31. var row = data[rowKey];
  32. var rowValues = [];
  33. if(typeof row == 'object'){
  34. rowValues = Object.keys(row).map(function(k){
  35. return row[k];
  36. });
  37. }
  38. table.push([rowKey].concat(rowValues));
  39. });
  40. console.log(table.toString());
  41. function calculateColWidth (item) {
  42. var MAX_COL_WIDTH = 28;
  43. var MIN_COL_WIDTH = 3;
  44. var width = null;
  45. if(item.toString){
  46. if(item.toString().length > MAX_COL_WIDTH)
  47. width = MAX_COL_WIDTH;
  48. if(item.toString().length < MIN_COL_WIDTH)
  49. width = MIN_COL_WIDTH;
  50. else if(!width)
  51. width = item.toString().length;
  52. }else{
  53. width = MAX_COL_WIDTH;
  54. }
  55. return width + 2;
  56. }
  57. };