table.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const stripAnsi = require('strip-ansi')
  2. function normalizeCols (rows, max) {
  3. function padEnd (string, maxLength, fillString) {
  4. while ((stripAnsi(string) + '').length < maxLength) {
  5. string = string + fillString
  6. }
  7. return string
  8. }
  9. var widths = []
  10. max = max || rows[0].length
  11. for (var i = 0; i < rows.length; i++) {
  12. for (var j = 0; j < rows[i].length && j < max; j++) {
  13. if (!widths[j] || widths[j] < (stripAnsi(rows[i][j]) + '').length) {
  14. widths[j] = (stripAnsi(rows[i][j] + '') + '').length
  15. }
  16. }
  17. }
  18. for (var i = 0; i < rows.length; i++) {
  19. for (var j = 0; j < rows[i].length && j < max; j++) {
  20. if (rows[i][j] == '-') {
  21. rows[i][j] = padEnd(rows[i][j], widths[j], '-')
  22. } else {
  23. rows[i][j] = padEnd(rows[i][j], widths[j], ' ')
  24. }
  25. }
  26. }
  27. return rows
  28. }
  29. function keyValueArray(columns, keys, obj) {
  30. ///console.log(columns, keys, obj)
  31. return keys.map(el => columns[el](obj))
  32. }
  33. module.exports.format = function (data, options) {
  34. //console.log(options)
  35. var keys = []
  36. var separators = []
  37. for(var key in options.columns) {
  38. keys.push(key)
  39. separators.push('-')
  40. }
  41. var items = [
  42. keys,
  43. separators,
  44. ...data.map(data => keyValueArray(options.columns, keys, data))
  45. ]
  46. items = normalizeCols(items).map(el => {
  47. return el.join(' | ').replace(/\n/g, '')
  48. }).join('\n')
  49. if (!options.color) { items = stripAnsi(items) }
  50. console.log(items)
  51. }