utils.js 1.8 KB

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