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.

163 lines
4.9 KiB

11 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
12 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. #!/usr/bin/env node
  2. "use strict";
  3. var dope = require("console-dope");
  4. var http = require("http");
  5. var cliArgs = require("command-line-args");
  6. var o = require("object-tools");
  7. var t = require("typical");
  8. var path = require("path");
  9. var loadConfig = require("config-master");
  10. var homePath = require("home-path");
  11. var logStats = require("stream-log-stats");
  12. var connect = require("connect");
  13. var morgan = require("morgan");
  14. var serveStatic = require("serve-static");
  15. var directory = require("serve-index");
  16. var compress = require("compression");
  17. var cliOptions = require("../lib/cli-options");
  18. var url = require("url");
  19. /* specify the command line arg definitions and usage forms */
  20. var cli = cliArgs(cliOptions);
  21. var usage = cli.getUsage({
  22. title: "[bold]{local-web-server}",
  23. description: "Lightweight static web server, zero configuration.",
  24. footer: "Project home: [underline]{https://github.com/75lb/local-web-server}",
  25. usage: {
  26. title: "[bold]{Usage}",
  27. forms: [
  28. "$ ws <server options>",
  29. "$ ws --config",
  30. "$ ws --help"
  31. ]
  32. },
  33. groups: {
  34. server: "[bold]{Server}",
  35. misc: "[bold]{Misc}"
  36. }
  37. });
  38. /* parse command line args */
  39. try {
  40. var wsOptions = cli.parse();
  41. } catch(err){
  42. halt(err.message);
  43. }
  44. /* Load and merge together options from
  45. - ~/.local-web-server.json
  46. - {cwd}/.local-web-server.json
  47. - the `local-web-server` property of {cwd}/package.json
  48. */
  49. var storedConfig = loadConfig(
  50. path.join(homePath(), ".local-web-server.json"),
  51. path.join(process.cwd(), ".local-web-server.json"),
  52. { jsonPath: path.join(process.cwd(), "package.json"), configProperty: "local-web-server" }
  53. );
  54. var builtInDefaults = {
  55. port: 8000,
  56. directory: process.cwd(),
  57. "refresh-rate": 500,
  58. mime: {}
  59. };
  60. /* override built-in defaults with stored config and then command line args */
  61. wsOptions.server = o.extend(builtInDefaults, storedConfig, wsOptions.server);
  62. /* user input validation */
  63. if (!t.isNumber(wsOptions.server.port)) {
  64. halt("please supply a numeric port value");
  65. }
  66. if (wsOptions.misc.config){
  67. dope.log("Stored config: ");
  68. dope.log(storedConfig);
  69. process.exit(0);
  70. } else if (wsOptions.misc.help){
  71. dope.log(usage);
  72. } else {
  73. process.on("SIGINT", function(){
  74. dope.showCursor();
  75. dope.log();
  76. process.exit(0);
  77. });
  78. dope.hideCursor();
  79. launchServer();
  80. /* write launch information to stderr (stdout is reserved for web log output) */
  81. if (path.resolve(wsOptions.server.directory) === process.cwd()){
  82. dope.error("serving at %underline{%s}", "http://localhost:" + wsOptions.server.port);
  83. } else {
  84. dope.error("serving %underline{%s} at %underline{%s}", wsOptions.server.directory, "http://localhost:" + wsOptions.server.port);
  85. }
  86. }
  87. function halt(message){
  88. dope.red.log("Error: %s", message);
  89. dope.log(usage);
  90. process.exit(1);
  91. }
  92. function launchServer(){
  93. var app = connect();
  94. /* enable cross-origin requests on all resources */
  95. app.use(function(req, res, next){
  96. res.setHeader("Access-Control-Allow-Origin", "*");
  97. next();
  98. });
  99. app.use(getLogger());
  100. /* --compress enables compression */
  101. if (wsOptions.server.compress) app.use(compress());
  102. /* set the mime-type overrides specified in the config */
  103. serveStatic.mime.define(wsOptions.server.mime);
  104. /* enable static file server, including directory browsing support */
  105. app.use(serveStatic(path.resolve(wsOptions.server.directory)))
  106. .use(directory(path.resolve(wsOptions.server.directory), { icons: true }));
  107. /* launch server */
  108. http.createServer(app)
  109. .on("error", function(err){
  110. if (err.code === "EADDRINUSE"){
  111. halt("port " + wsOptions.server.port + " is already is use");
  112. } else {
  113. halt(err.message);
  114. }
  115. })
  116. .listen(wsOptions.server.port);
  117. }
  118. function getLogger(){
  119. /* log using --log-format (if supplied) */
  120. var logFormat = wsOptions.server["log-format"];
  121. if(logFormat) {
  122. if (logFormat === "none"){
  123. // do nothing, no logging required
  124. } else {
  125. if (logFormat === "logstalgia"){
  126. /* customised logger :date token, purely to satisfy Logstalgia. */
  127. morgan.token("date", function(){
  128. var d = new Date();
  129. return (d.getDate() + "/" + d.getUTCMonth() + "/" + d.getFullYear() + ":" + d.toTimeString())
  130. .replace("GMT", "").replace(" (BST)", "");
  131. });
  132. logFormat = "combined";
  133. }
  134. return morgan(logFormat);
  135. }
  136. /* if no `--log-format` was specified, pipe the default format output
  137. into `log-stats`, which prints statistics to the console */
  138. } else {
  139. return morgan("common", { stream: logStats({ refreshRate: wsOptions.server["refresh-rate"] }) });
  140. }
  141. }