utils.js 1.8 KB

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