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.

158 lines
4.0 KiB

11 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
11 years ago
8 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
8 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 localWebServer = require('../')
  4. const cliOptions = require('../lib/cli-options')
  5. const commandLineArgs = require('command-line-args')
  6. const commandLineUsage = require('command-line-usage')
  7. const ansi = require('ansi-escape-sequences')
  8. const loadConfig = require('config-master')
  9. const path = require('path')
  10. const os = require('os')
  11. const arrayify = require('array-back')
  12. const t = require('typical')
  13. const flatten = require('reduce-flatten')
  14. const usage = commandLineUsage(cliOptions.usageData)
  15. const stored = loadConfig('local-web-server')
  16. let options
  17. let isHttps = false
  18. try {
  19. options = collectOptions()
  20. } catch (err) {
  21. stop([ `[red]{Error}: ${err.message}`, usage ], 1)
  22. return
  23. }
  24. if (options.misc.help) {
  25. stop(usage, 0)
  26. } else if (options.misc.config) {
  27. stop(JSON.stringify(options.server, null, ' '), 0)
  28. } else {
  29. const valid = validateOptions(options)
  30. if (!valid) {
  31. /* gracefully end the process */
  32. return
  33. }
  34. const app = localWebServer({
  35. static: {
  36. root: options.server.directory,
  37. options: {
  38. hidden: true
  39. }
  40. },
  41. serveIndex: {
  42. path: options.server.directory,
  43. options: {
  44. icons: true,
  45. hidden: true
  46. }
  47. },
  48. log: {
  49. format: options.server['log-format']
  50. },
  51. compress: options.server.compress,
  52. mime: options.server.mime,
  53. forbid: options.server.forbid,
  54. spa: options.server.spa,
  55. 'no-cache': options.server['no-cache'],
  56. rewrite: options.server.rewrite,
  57. verbose: options.server.verbose,
  58. mocks: options.server.mocks
  59. })
  60. app.on('error', err => {
  61. if (options.server['log-format']) {
  62. console.error(ansi.format(err.message, 'red'))
  63. }
  64. })
  65. if (options.server.https) {
  66. options.server.key = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.key')
  67. options.server.cert = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.crt')
  68. }
  69. if (options.server.key && options.server.cert) {
  70. const https = require('https')
  71. const fs = require('fs')
  72. isHttps = true
  73. const serverOptions = {
  74. key: fs.readFileSync(options.server.key),
  75. cert: fs.readFileSync(options.server.cert)
  76. }
  77. const server = https.createServer(serverOptions, app.callback())
  78. server.listen(options.server.port, onServerUp)
  79. } else {
  80. app.listen(options.server.port, onServerUp)
  81. }
  82. }
  83. function stop (msgs, exitCode) {
  84. arrayify(msgs).forEach(msg => console.error(ansi.format(msg)))
  85. process.exitCode = exitCode
  86. }
  87. function onServerUp () {
  88. let ipList = Object.keys(os.networkInterfaces())
  89. .map(key => os.networkInterfaces()[key])
  90. .reduce(flatten, [])
  91. .filter(iface => iface.family === 'IPv4')
  92. ipList.unshift({ address: os.hostname() })
  93. ipList = ipList
  94. .map(iface => `[underline]{${isHttps ? 'https' : 'http'}://${iface.address}:${options.server.port}}`)
  95. .join(', ')
  96. console.error(ansi.format(
  97. path.resolve(options.server.directory) === process.cwd()
  98. ? `serving at ${ipList}`
  99. : `serving [underline]{${options.server.directory}} at ${ipList}`
  100. ))
  101. }
  102. function collectOptions () {
  103. let options = {}
  104. /* parse command line args */
  105. options = commandLineArgs(cliOptions.definitions)
  106. const builtIn = {
  107. port: 8000,
  108. directory: process.cwd(),
  109. forbid: [],
  110. rewrite: []
  111. }
  112. if (options.server.rewrite) {
  113. options.server.rewrite = parseRewriteRules(options.server.rewrite)
  114. }
  115. /* override built-in defaults with stored config and then command line args */
  116. options.server = Object.assign(builtIn, stored, options.server)
  117. return options
  118. }
  119. function parseRewriteRules (rules) {
  120. return rules && rules.map(rule => {
  121. const matches = rule.match(/(\S*)\s*->\s*(\S*)/)
  122. return {
  123. from: matches[1],
  124. to: matches[2]
  125. }
  126. })
  127. }
  128. function validateOptions (options) {
  129. let valid = true
  130. function invalid (msg) {
  131. return `[red underline]{Invalid:} [bold]{${msg}}`
  132. }
  133. if (!t.isNumber(options.server.port)) {
  134. stop([ invalid(`--port must be numeric`), usage ], 1)
  135. valid = false
  136. }
  137. return valid
  138. }