cncjs

Форк
0
/
server-cli.js 
119 строк · 4.3 Кб
1
/* eslint-disable no-console */
2
/* eslint no-console: 0 */
3
require('core-js/stable'); // to polyfill ECMAScript features
4
require('regenerator-runtime/runtime'); // needed to use transpiled generator functions
5

6
const path = require('path');
7
const isElectron = require('is-electron');
8
const program = require('commander');
9
const pkg = require('./package.json');
10

11
// Defaults to 'production'
12
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
13

14
const increaseVerbosityLevel = (val, total) => {
15
  return total + 1;
16
};
17

18
const parseMountPoint = (val, acc) => {
19
  val = val || '';
20

21
  const mount = {
22
    route: '/',
23
    target: val
24
  };
25

26
  if (val.indexOf(':') >= 0) {
27
    const r = val.match(/(?:([^:]*)(?::(.*)))/);
28
    mount.route = r[1];
29
    mount.target = r[2];
30
  }
31

32
  // mount.route is interpreted by cncjs code that uses posix syntax
33
  // where the separator is / , so we perform this join in posix mode
34
  // mode to avoid introducing \ separators when running on Windows.
35
  mount.route = path.posix.join('/', mount.route || '').trim(); // path.join('/', 'pendant') => '/pendant'
36
  mount.target = (mount.target || '').trim();
37

38
  acc.push(mount);
39

40
  return acc;
41
};
42

43
const parseController = (val) => {
44
  val = val ? (val + '').toLowerCase() : '';
45

46
  if (['grbl', 'marlin', 'smoothie', 'tinyg', 'g2core'].includes(val)) {
47
    return val;
48
  } else {
49
    return '';
50
  }
51
};
52

53
const defaultHost = isElectron() ? '127.0.0.1' : '0.0.0.0';
54
const defaultPort = isElectron() ? 0 : 8000;
55

56
program
57
  .version(pkg.version, '--version', 'output the current version')
58
  .usage('[options]')
59
  .option('-p, --port <port>', `Set listen port (default: ${defaultPort})`, defaultPort)
60
  .option('-H, --host <host>', `Set listen address or hostname (default: ${defaultHost})`, defaultHost)
61
  .option('-b, --backlog <backlog>', 'Set listen backlog (default: 511)', 511)
62
  .option('-c, --config <filename>', 'Set config file (default: ~/.cncrc)')
63
  .option('-v, --verbose', 'Increase the verbosity level (-v, -vv, -vvv)', increaseVerbosityLevel, 0)
64
  .option('-m, --mount <route-path>:<target>', 'Add a mount point for serving static files', parseMountPoint, [])
65
  .option('-w, --watch-directory <path>', 'Watch a directory for changes')
66
  .option('--access-token-lifetime <lifetime>', 'Access token lifetime in seconds or a time span string (default: 30d)')
67
  .option('--allow-remote-access', 'Allow remote access to the server (default: false)')
68
  .option('--controller <type>', 'Specify CNC controller: Grbl|Marlin|Smoothie|TinyG|g2core (default: \'\')', parseController, '');
69

70
program.on('--help', () => {
71
  console.log('');
72
  console.log('  Examples:');
73
  console.log('');
74
  console.log('    $ cncjs -vv');
75
  console.log('    $ cncjs --mount /pendant:/home/pi/tinyweb');
76
  console.log('    $ cncjs --mount /widget:~+/widget --mount /pendant:~/pendant');
77
  console.log('    $ cncjs --mount /widget:https://cncjs.github.io/cncjs-widget-boilerplate/v1/');
78
  console.log('    $ cncjs --watch-directory /home/pi/watch');
79
  console.log('    $ cncjs --access-token-lifetime 60d  # e.g. 3600, 30m, 12h, 30d');
80
  console.log('    $ cncjs --allow-remote-access');
81
  console.log('    $ cncjs --controller Grbl');
82
  console.log('');
83
});
84

85
// Commander assumes that the first two values in argv are 'node' and appname, and then followed by the args.
86
// This is not the case when running from a packaged Electron app. Here you have the first value appname and then args.
87
const normalizedArgv = ('' + process.argv[0]).indexOf(pkg.name) >= 0
88
  ? ['node', pkg.name, ...process.argv.slice(1)]
89
  : process.argv;
90
if (normalizedArgv.length > 1) {
91
  program.parse(normalizedArgv);
92
}
93

94
const options = program.opts();
95

96
module.exports = () => new Promise((resolve, reject) => {
97
  // Change working directory to 'server' before require('./server')
98
  process.chdir(path.resolve(__dirname, 'server'));
99

100
  require('./server').createServer({
101
    port: options.port,
102
    host: options.host,
103
    backlog: options.backlog,
104
    configFile: options.config,
105
    verbosity: options.verbose,
106
    mountPoints: options.mount,
107
    watchDirectory: options.watchDirectory,
108
    accessTokenLifetime: options.accessTokenLifetime,
109
    allowRemoteAccess: !!options.allowRemoteAccess,
110
    controller: options.controller
111
  }, (err, data) => {
112
    if (err) {
113
      reject(err);
114
      return;
115
    }
116

117
    resolve(data);
118
  });
119
});
120

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.