utils.js 1.7 KB

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