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.

69 lines
2.1 KiB

11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
  1. #!/usr/bin/env node
  2. 'use strict'
  3. const localWebServer = require('../')
  4. const streamLogStats = require('stream-log-stats')
  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 options = {}
  11. /* parse command line args */
  12. const cli = commandLineArgs(cliOptions.definitions)
  13. const usage = cli.getUsage(cliOptions.usageData)
  14. try {
  15. options.cli = cli.parse()
  16. } catch (err) {
  17. halt(err.message)
  18. }
  19. options.stored = loadConfig('local-web-server')
  20. options.builtIn = {
  21. port: 8000,
  22. directory: process.cwd(),
  23. 'refresh-rate': 500,
  24. mime: {}
  25. }
  26. /* override built-in defaults with stored config and then command line args */
  27. options.cli.server = Object.assign(options.builtIn, options.stored, options.cli.server)
  28. if (options.cli.misc.help) return console.log(usage)
  29. if (options.cli.misc.config) return console.log(JSON.stringify(options.stored, null, ' '))
  30. let log = {
  31. format: options.cli.server['log-format']
  32. }
  33. if (log.format === 'none'){
  34. log.format = undefined
  35. } else if (log.format){
  36. log.stream = process.stdout
  37. } else {
  38. log.format = 'common'
  39. log.stream = streamLogStats({ refreshRate: 100 })
  40. }
  41. localWebServer({
  42. static: { root: options.cli.server.directory },
  43. serveIndex: { path: options.cli.server.directory, options: { icons: true } },
  44. logger: { format: log.format, options: { stream: log.stream } }
  45. }).listen(options.cli.server.port, serverUp)
  46. function halt (message) {
  47. console.log(ansi.format(`Error: ${message}`, 'red'))
  48. console.log(usage)
  49. process.exit(1)
  50. }
  51. function serverUp () {
  52. /* write launch information to stderr (stdout is reserved for web log output) */
  53. if (path.resolve(options.cli.server.directory) === process.cwd()) {
  54. console.error(ansi.format(`serving at [underline]{http://localhost:${options.cli.server.port}}`))
  55. } else {
  56. console.error(ansi.format(`serving [underline]{options.cli.server.directory} at [underline]{http://localhost:${options.cli.server.port}}`))
  57. }
  58. }