index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. var util = require('util');
  3. var Console = require('console').Console;
  4. var supportsColor = require('color-support');
  5. var console = new Console({
  6. stdout: process.stdout,
  7. stderr: process.stderr,
  8. colorMode: false,
  9. });
  10. function hasFlag(flag) {
  11. return process.argv.indexOf('--' + flag) !== -1;
  12. }
  13. function hasColors() {
  14. if (hasFlag('no-color')) {
  15. return false;
  16. }
  17. if (hasFlag('color')) {
  18. return true;
  19. }
  20. if (supportsColor()) {
  21. return true;
  22. }
  23. return false;
  24. }
  25. function Timestamp() {
  26. this.now = new Date();
  27. }
  28. Timestamp.prototype[util.inspect.custom] = function (depth, opts) {
  29. var timestamp = this.now.toLocaleTimeString('en', { hour12: false });
  30. return '[' + opts.stylize(timestamp, 'date') + ']';
  31. };
  32. function getTimestamp() {
  33. return util.inspect(new Timestamp(), { colors: hasColors() });
  34. }
  35. function log() {
  36. var time = getTimestamp();
  37. process.stdout.write(time + ' ');
  38. console.log.apply(console, arguments);
  39. return this;
  40. }
  41. function info() {
  42. var time = getTimestamp();
  43. process.stdout.write(time + ' ');
  44. console.info.apply(console, arguments);
  45. return this;
  46. }
  47. function dir() {
  48. var time = getTimestamp();
  49. process.stdout.write(time + ' ');
  50. console.dir.apply(console, arguments);
  51. return this;
  52. }
  53. function warn() {
  54. var time = getTimestamp();
  55. process.stderr.write(time + ' ');
  56. console.warn.apply(console, arguments);
  57. return this;
  58. }
  59. function error() {
  60. var time = getTimestamp();
  61. process.stderr.write(time + ' ');
  62. console.error.apply(console, arguments);
  63. return this;
  64. }
  65. module.exports = log;
  66. module.exports.info = info;
  67. module.exports.dir = dir;
  68. module.exports.warn = warn;
  69. module.exports.error = error;