utils.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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)
  27. return resolve(port);
  28. const message = `Something is already running on port ${defaultPort}.`;
  29. if (isInteractive) {
  30. clearConsole();
  31. const question = {
  32. type: 'confirm',
  33. name: 'changePort',
  34. message:
  35. chalk.yellow(message)
  36. + '\nWould you like to run the app on another port instead?',
  37. initial: true,
  38. };
  39. prompts(question).then(function({changePort}) {
  40. changePort ? resolve(port) : resolve(null);
  41. });
  42. } else {
  43. console.log(chalk.red(message));
  44. resolve(null);
  45. }
  46. });
  47. },
  48. function(err) {
  49. throw new Error(
  50. chalk.red(`Could not find an open port at ${chalk.bold(host)}.`)
  51. + '\n'
  52. + ('Network error message: ' + err.message || err)
  53. + '\n',
  54. );
  55. },
  56. );
  57. }
  58. module.exports = {
  59. clearConsole,
  60. startedServerLogger,
  61. errorLogger,
  62. junglePort,
  63. };