index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. const ChildProcess = require('child_process').ChildProcess;
  3. const Console = require('console').Console;
  4. const through = require('through2');
  5. const split = require('split2');
  6. const pumpify = require('pumpify');
  7. const defaults = {
  8. stdout: process.stdout,
  9. stderr: process.stderr,
  10. prefix: '',
  11. time: true,
  12. };
  13. /**
  14. * log/debug/info -> this.stdout(pad) -> opt.stdout
  15. * warn/error -> this.stderr(pad) -> opt.stderr
  16. */
  17. class Logger extends Console {
  18. constructor(options) {
  19. options = Object.assign({}, defaults, options);
  20. const stdout = padStream(() => this._getPrefix());
  21. const stderr = padStream(() => this._getPrefix());
  22. super(stdout, stderr);
  23. this.stdout = stdout;
  24. this.stderr = stderr;
  25. this.options = options;
  26. stdout.setMaxListeners(100);
  27. stderr.setMaxListeners(100);
  28. stdout.pipe(options.stdout);
  29. stderr.pipe(options.stderr);
  30. }
  31. child(obj, prefix) {
  32. // child('> ')
  33. if (typeof obj === 'string') {
  34. prefix = obj;
  35. obj = null;
  36. }
  37. // obj -> child.stdout/stderr(pad) -> this.stdout/stderr(pad) -> opt.stdout
  38. const child = new Logger({
  39. stdout: this.stdout,
  40. stderr: this.stderr,
  41. time: false,
  42. prefix: prefix || '',
  43. });
  44. if (obj) {
  45. if (obj instanceof ChildProcess) {
  46. obj.stdout.pipe(child.stdout, { end: false });
  47. obj.stderr.pipe(child.stderr, { end: false });
  48. } else if (obj.pipe) {
  49. obj.pipe(child.stdout, { end: false });
  50. }
  51. }
  52. return child;
  53. }
  54. end() {
  55. this.stdout.end();
  56. this.stderr.end();
  57. }
  58. _getPrefix() {
  59. let prefix = this.options.prefix;
  60. if (typeof prefix === 'function') {
  61. prefix = prefix();
  62. }
  63. if (!this.options.time) return prefix;
  64. const d = new Date();
  65. let hours = d.getHours();
  66. if (hours < 10) {
  67. hours = '0' + hours;
  68. }
  69. let mintues = d.getMinutes();
  70. if (mintues < 10) {
  71. mintues = '0' + mintues;
  72. }
  73. let seconds = d.getSeconds();
  74. if (seconds < 10) {
  75. seconds = '0' + seconds;
  76. }
  77. return `[${hours}:${mintues}:${seconds}] ${prefix}`;
  78. }
  79. }
  80. module.exports = Logger;
  81. function padStream(prefix) {
  82. return pumpify(split(), through(function(data, enc, cb) {
  83. this.push(prefix());
  84. this.push(data);
  85. this.push('\n');
  86. cb();
  87. }));
  88. }