utils.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const chalk = require('chalk');
  2. const detect = require('detect-port-alt');
  3. const prompts = require('prompts');
  4. function clearConsole() {
  5. process.stdout.write(
  6. process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H',
  7. );
  8. }
  9. function startedServerLogger(port, host) {
  10. console.log();
  11. console.log(chalk.green('Server started! 🥰'));
  12. console.log();
  13. console.log(
  14. `Network: ${chalk.hex('#db5a6b').bold(`http://${host}:${port}`)}`,
  15. );
  16. console.log();
  17. }
  18. function errorLogger(error) {
  19. console.error(chalk.red(error + ' 😭'));
  20. }
  21. function junglePort(host, defaultPort) {
  22. const isInteractive = process.stdout.isTTY;
  23. return detect(defaultPort, host).then(
  24. function (port) {
  25. return new Promise(function (resolve) {
  26. if (port === defaultPort) return resolve(port);
  27. const message = `Something is already running on port ${defaultPort}.`;
  28. if (isInteractive) {
  29. clearConsole();
  30. const question = {
  31. type: 'confirm',
  32. name: 'changePort',
  33. message:
  34. chalk.yellow(message) +
  35. '\nWould you like to run the app on another port instead?',
  36. initial: true,
  37. };
  38. prompts(question).then(function ({changePort}) {
  39. changePort ? resolve(port) : resolve(null);
  40. });
  41. } else {
  42. console.log(chalk.red(message));
  43. resolve(null);
  44. }
  45. });
  46. },
  47. function (err) {
  48. throw new Error(
  49. chalk.red(`Could not find an open port at ${chalk.bold(host)}.`) +
  50. '\n' +
  51. ('Network error message: ' + err.message || err) +
  52. '\n',
  53. );
  54. },
  55. );
  56. }
  57. module.exports = {
  58. clearConsole,
  59. startedServerLogger,
  60. errorLogger,
  61. junglePort,
  62. };