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.

84 lines
2.5 KiB

11 years ago
11 years ago
11 years ago
12 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. #!/usr/bin/env node
  2. var connect = require("connect"),
  3. http = require("http"),
  4. util = require("util"),
  5. Thing = require("nature").Thing,
  6. wodge = require("wodge");
  7. var usage = "usage: ws [--directory|-d <directory>] [--port|-p <port>] [--log-format|-f dev|default|short|tiny]";
  8. var options = new Thing()
  9. .define({ name: "port", alias: "p", type: "number", defaultOption: true, value: 8000 })
  10. .define({ name: "log-format", alias: "f", type: "string", value: "dev" })
  11. .define({ name: "help", alias: "h", type: "boolean" })
  12. .define({ name: "directory", alias: "d", type: "string", value: process.cwd() })
  13. .define({ name: "stats", alias: "s", type: "boolean" })
  14. .on("error", function(err){
  15. halt(err.message);
  16. })
  17. .set(process.argv);
  18. function handleServerError(err){
  19. if (err.code === "EADDRINUSE"){
  20. halt("port " + options.port + " is already is use");
  21. } else {
  22. halt(err.message);
  23. }
  24. }
  25. function halt(message){
  26. console.log(wodge.red("Error ") + message);
  27. console.log(usage);
  28. process.exit(1);
  29. }
  30. if (!options.valid){
  31. halt(options.validationMessages);
  32. } else if (options.help){
  33. console.log(usage);
  34. } else {
  35. /**
  36. customised connect.logger :date token, purely to satisfy Logstalgia.
  37. */
  38. connect.logger.token("date", function(){
  39. var a = new Date();
  40. return (a.getDate() + "/" + a.getUTCMonth() + "/" + a.getFullYear() + ":" + a.toTimeString())
  41. .replace("GMT", "").replace(" (BST)", "");
  42. });
  43. var app = connect();
  44. if(options.stats){
  45. var reqCount = 0;
  46. app.use(function(req, res, next){
  47. if (reqCount === 0){
  48. process.stdout.write("Files served: ");
  49. }
  50. process.stdout.write(reqCount.toString());
  51. reqCount++;
  52. process.stdout.write("\x1b[15G");
  53. next();
  54. });
  55. } else {
  56. app.use(connect.logger(options["log-format"]));
  57. }
  58. app.use(connect.compress())
  59. .use(connect.static(options.directory))
  60. .use(connect.directory(options.directory, { icons: true }));
  61. http.createServer(app)
  62. .on("error", handleServerError)
  63. .listen(options.port);
  64. /*
  65. write to stderr so stdout can be piped to disk ($ ws > log.txt)
  66. */
  67. console.error(util.format(
  68. "serving %sat %s",
  69. options.directory === process.cwd() ? "" : wodge.underline(options.directory) + " ",
  70. wodge.underline("http://localhost:" + options.port)
  71. ));
  72. }