main.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env node
  2. // Gestion du signal d'arret (SIGINT = Ctrl+C)
  3. process.on('SIGINT', function () {
  4. console.info("\nStopping the server");
  5. process.exit();
  6. });
  7. // Gestion des commandes et des options de l'application
  8. const argv = require('yargs')
  9. .command('serve [port]', 'start the Loquicompta server', (yargs) => {
  10. yargs.positional('port', {describe: 'port to bind', default: 80});
  11. }, (argv) => {
  12. })
  13. .command('dev', 'start the Loquicompta server on 8080 port with verbose', (yargs) => {
  14. }, (argv) => {
  15. argv.port = 8080;
  16. argv.verbose = 1;
  17. })
  18. .option('port', {
  19. alias: 'p',
  20. default: 80
  21. })
  22. .option('auth', {
  23. default: true
  24. })
  25. .count('verbose')
  26. .alias('v', 'verbose')
  27. .count('sql')
  28. .alias('s', 'sql')
  29. .describe('p', 'port to bind')
  30. .describe('auth', 'disables authentication')
  31. .describe('v', 'show server informations')
  32. .describe('s', 'show sql informations')
  33. .argv;
  34. // Chargement fichier config
  35. const config = require('./src/config');
  36. // Bibliotheques
  37. const express = require('express');
  38. const portfinder = require('portfinder');
  39. // Creation variable globale
  40. global.app = express();
  41. if (!config.auth) {
  42. global.auth = false;
  43. } else {
  44. global.auth = argv.auth;
  45. }
  46. global.storage = config.storage;
  47. global.verbose = argv.verbose >= 1;
  48. global.sqlVerbose = argv.sql >= 1;
  49. // Configuration server
  50. app.use(express.json());
  51. require('./src/route');
  52. // Lancement serveur sur le port demandé
  53. portfinder.basePort = argv.port;
  54. portfinder.highestPort = argv.port;
  55. portfinder.getPortPromise()
  56. .then((port) => {
  57. app.listen(argv.port, () => {
  58. console.info(`Server starting on port ${port} (http://localhost:${port})`);
  59. });
  60. })
  61. .catch((err) => {
  62. if (err.toString().includes('Error: No open ports') && config.findPort) {
  63. console.info(`Port ${argv.port} not available, search for a new available port`);
  64. // Recherche d'un port ouvert
  65. portfinder.basePort = 8000;
  66. portfinder.highestPort = 65535;
  67. portfinder.getPortPromise()
  68. .then((port) => {
  69. app.listen(port, () => {
  70. console.info(`New available port found: ${port}`);
  71. console.info(`Server starting on port ${port} (http://localhost:${port})`);
  72. });
  73. })
  74. .catch((err) => {
  75. console.err(err);
  76. console.info('Unable to start the server, end of execution');
  77. process.exit();
  78. });
  79. } else {
  80. console.error(err.toString());
  81. console.info('Unable to start the server, end of execution');
  82. process.exit();
  83. }
  84. });