Nav apraksta

tiny-lr-fork 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env node
  2. var fs = require('fs');
  3. var path = require('path');
  4. // default DEBUG if not set already
  5. process.env.DEBUG = process.env.DEBUG || 'tinylr tinylr:*';
  6. var Server = require('..').Server;
  7. var noptify = require('noptify');
  8. var program = noptify(process.argv, { program: 'tiny-lr' })
  9. .version('0.0.1')
  10. .option('port', '-p', 'Port to listen on (default: 35729)', Number)
  11. .option('pid', 'Path to the generated PID file (default: ./tiny-lr.pid)', String);
  12. var opts = program.parse();
  13. opts.port = opts.port || 35729;
  14. opts.pid = opts.pid || path.resolve('tiny-lr.pid');
  15. // if it was required, don't start the server and expose the Server object.
  16. if (module.parent) {
  17. module.exports = Server;
  18. return;
  19. }
  20. // Server
  21. // Thanks to @FGRibreau for his very simple and very handy gist:
  22. // https://gist.github.com/1846952
  23. process.title = 'tiny-lr';
  24. process.on('exit', function() {
  25. console.log('... Closing server ...');
  26. console.log('... Removing pid file (%s) ...', opts.pid);
  27. fs.unlinkSync(opts.pid);
  28. });
  29. process.on('SIGTERM', function() {
  30. return process.exit(0);
  31. });
  32. process.on('SIGINT', function() {
  33. return process.exit(0);
  34. });
  35. var srv = new Server(opts);
  36. srv.on('close', function() {
  37. process.nextTick(function() {
  38. process.exit();
  39. });
  40. });
  41. console.log();
  42. srv.listen(opts.port, function(err) {
  43. fs.writeFile(opts.pid, process.pid, function(err) {
  44. if(err) {
  45. console.log('... Cannot write pid file: %s', opts.pid);
  46. process.exit(1)
  47. }
  48. console.log('... Listening on %s (pid: %s) ...', opts.port, process.pid);
  49. console.log('... pid file: %s', opts.pid);
  50. });
  51. });