cli.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const { readFileSync } = require('fs');
  2. const { resolve } = require('path');
  3. const cli = require('commander');
  4. const { version } = require('../package.json');
  5. const { createServer } = require('./server');
  6. const optionNames = [
  7. 'socks',
  8. 'port',
  9. 'level',
  10. 'config',
  11. 'host',
  12. ];
  13. function getFileConfig(filePath) {
  14. const absFile = resolve(process.cwd(), filePath);
  15. const content = readFileSync(absFile).toString('utf8');
  16. let fileConfig = null;
  17. try {
  18. fileConfig = JSON.parse(content);
  19. } catch (err) {
  20. const error = new Error(`invalid json content: ${err.message}`);
  21. error.code = err.code;
  22. throw error;
  23. }
  24. return fileConfig;
  25. }
  26. function getOptionsArgs(args) {
  27. const options = {};
  28. optionNames.forEach((name) => {
  29. if (Object.hasOwnProperty.apply(args, [name])) {
  30. if (typeof args[name] !== 'string') {
  31. throw new Error(`string "${name}" expected`);
  32. }
  33. options[name] = args[name];
  34. }
  35. });
  36. return options;
  37. }
  38. function main() {
  39. cli.version(version)
  40. .option('-s, --socks [socks]', 'specify your socks proxy host, default: 127.0.0.1:1080')
  41. .option('-p, --port [port]', 'specify the listening port of http proxy server, default: 8080')
  42. .option('-l, --host [host]', 'specify the listening host of http proxy server, default: 127.0.0.1')
  43. .option('-c, --config [config]', 'read configs from file in json format')
  44. .option('--level [level]', 'log level, vals: info, error')
  45. .parse(process.argv);
  46. const options = getOptionsArgs(cli);
  47. let fileConfig = null;
  48. if (options.config) {
  49. fileConfig = getFileConfig(options.config);
  50. }
  51. Object.assign(options, fileConfig);
  52. createServer(options);
  53. }
  54. module.exports = {
  55. getOptionsArgs,
  56. main,
  57. };