You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.2 KiB

11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. #!/usr/bin/env node
  2. 'use strict'
  3. const s = Date.now()
  4. const localWebServer = require('../')
  5. const commandLineArgs = require('command-line-args')
  6. const ansi = require('ansi-escape-sequences')
  7. const cliOptions = require('../lib/cli-options')
  8. const loadConfig = require('config-master')
  9. const path = require('path')
  10. const cli = commandLineArgs(cliOptions.definitions)
  11. const usage = cli.getUsage(cliOptions.usageData)
  12. const stored = loadConfig('local-web-server')
  13. const options = collectOptions()
  14. if (options.misc.help) {
  15. console.log(usage)
  16. process.exit(0)
  17. }
  18. if (options.misc.config) {
  19. console.log(JSON.stringify(stored, null, ' '))
  20. process.exit(0)
  21. }
  22. localWebServer({
  23. static: {
  24. root: options.server.directory,
  25. options: {
  26. hidden: true
  27. }
  28. },
  29. serveIndex: {
  30. path: options.server.directory,
  31. options: {
  32. icons: true,
  33. hidden: true
  34. }
  35. },
  36. log: { format: options.server['log-format'] },
  37. compress: options.server.compress,
  38. mime: options.server.mime,
  39. forbid: options.server.forbid.map(regexp => RegExp(regexp, "i")),
  40. proxyRoutes: options.server.proxyRoutes,
  41. spa: options.server.spa,
  42. 'no-cache': options.server['no-cache']
  43. }).listen(options.server.port, onServerUp)
  44. function halt (err) {
  45. console.log(ansi.format(`Error: ${err.message}`, 'red'))
  46. console.log(usage)
  47. process.exit(1)
  48. }
  49. function onServerUp () {
  50. const e = Date.now()
  51. const time = `${e-s}ms`
  52. console.error(ansi.format(
  53. path.resolve(options.server.directory) === process.cwd()
  54. ? `serving at [underline]{http://localhost:${options.server.port}} ${time}`
  55. : `serving [underline]{${options.server.directory}} at [underline]{http://localhost:${options.server.port}} ${time}`
  56. ))
  57. }
  58. function collectOptions () {
  59. let options = {}
  60. /* parse command line args */
  61. try {
  62. options = cli.parse()
  63. } catch (err) {
  64. halt(err)
  65. }
  66. const builtIn = {
  67. port: 8000,
  68. root: process.cwd(), // root dir when using multiple static dirs
  69. directory: process.cwd(),
  70. proxyRoutes: [],
  71. forbid: []
  72. }
  73. /* override built-in defaults with stored config and then command line args */
  74. options.server = Object.assign(builtIn, stored, options.server)
  75. return options
  76. }