Permalink
Browse files

Fixed up the server and added dependencies to package.json.

  • Loading branch information...
papandreou committed Dec 27, 2011
1 parent fe9b0e3 commit 7651c54ffce679f008cb6a35aad8849b845c9b69
Showing with 104 additions and 52 deletions.
  1. +1 −0 .gitignore
  2. +24 −50 bin/livestyle
  3. +69 −0 lib/installLiveCssFileWatcherInServer.js
  4. +10 −2 package.json
View
@@ -0,0 +1 @@
+/node_modules/
View
@@ -1,58 +1,32 @@
#!/usr/bin/env node
-/*jslint nomen:false, regexp:true*/
-/*global module, require, __dirname, console, process*/
+/*jslint nomen:false */
+/*global require, __dirname */
var express = require('express'),
util = require('util'),
fs = require('fs'),
path = require('path'),
- error = require('./modules/error');
-
-
-
-function createServer (environment) {
- var app = module.exports = express.createServer();
-
- app.configure(function () {
- app.use(express.logger());
- if (app.set('gzip')) {
- app.use(express.gzip());
- }
- app.use(function (err, req, res, next) {
- if (err) {
- err = error.normalize(err);
- if (environment === 'development' && req.accepts('html')) {
- // Let errors pass through in development mode to get a nice stack trace
- return next(err);
- } else {
- return res.send({error: err.msg}, {'Content-Type': 'application/json'}, err.httpStatus || 500);
- }
- } else {
- next();
- }
- });
- });
-
- if (environment === 'production') {
- app.use(express['static'](__dirname + '/../http-pub-production'));
- app.use(express.errorHandler());
- }
-
- if (environment === 'development') {
- var dir = path.resolve(__dirname, '../http-pub');
- app.use(express['static'](dir));
- app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
- require('assetgraph-builder/lib/installLiveCssFileWatcherInServer')(app, dir, require('socket.io'));
- }
-
- // Listen if invoked directly using the node executable:
- return app;
-}
-
-createServer('development').listen(3000);
-createServer('production').listen(3001);
-
-process.on('uncaughtException', function (e) {
- util.error(e.stack);
+ app = express.createServer(),
+ commandLineOptions = require('optimist')
+ .usage('Usage: $0 [-p <portNumber>] [-h <hostName>] publicDir')
+ .default('host', '0.0.0.0')
+ .alias('host', 'h')
+ .default('port', 3000)
+ .alias('port', 'p')
+ .argv,
+ publicDir = path.normalize(commandLineOptions._[0] || process.cwd());
+
+app.configure(function () {
+ app
+ .use(express.logger())
+ .use(require('../lib/middleware/injectLiveStyleScriptIncludeIntoHtml')())
+ .use(express['static'](publicDir))
+ .use(express.errorHandler({dumpExceptions: true, showStack: true}));
+
+ require('../lib/installLiveCssFileWatcherInServer')(app, publicDir, require('socket.io'));
});
+app.listen(commandLineOptions.port, commandLineOptions.host);
+
+console.log('Serving static files from ' + publicDir);
+console.log('Listening to http://' + commandLineOptions.host + ':' + commandLineOptions.port + '/');
@@ -0,0 +1,69 @@
+var fs = require('fs'),
+ path = require('path'),
+ URL = require('url'),
+ clientsByFileName = {};
+
+function buildRelativeUrl(fromUrl, toUrl) {
+ var minLength = Math.min(fromUrl.length, toUrl.length),
+ commonPrefixLength = 0;
+ while (commonPrefixLength < minLength && fromUrl[commonPrefixLength] === toUrl[commonPrefixLength]) {
+ commonPrefixLength += 1;
+ }
+ var commonPrefix = fromUrl.substr(0, commonPrefixLength),
+ commonPrefixMatch = commonPrefix.match(/^(file:\/\/|[^:]+:\/\/[^\/]+\/)/);
+
+ if (commonPrefixMatch) {
+ var fromFragments = fromUrl.substr(commonPrefixMatch[1].length).replace(/^\/+/, "").replace(/[^\/]+$/, "").split(/\//),
+ toFragments = toUrl.substr(commonPrefixMatch[1].length).replace(/^\/+/, "").split(/\//);
+
+ fromFragments.pop();
+
+ var i = 0;
+ while (i < fromFragments.length && i < toFragments.length && fromFragments[i] === toFragments[i]) {
+ i += 1;
+ }
+ var relativeUrl = toFragments.slice(i).join("/");
+ while (i < fromFragments.length) {
+ relativeUrl = '../' + relativeUrl;
+ i += 1;
+ }
+ return relativeUrl;
+ } else {
+ return toUrl; // No dice
+ }
+}
+
+module.exports = function (app, dirName, sio) {
+ var io = sio.listen(app);
+ io.sockets.on('connection', function (client) {
+ client.on('watch', function (assetUrls, pageUrl) {
+ client.baseDir = dirName.replace(/\/$/, "") + path.dirname(URL.parse(pageUrl).pathname);
+ assetUrls.forEach(function (assetUrl) {
+ var rootRelativePath = URL.parse(URL.resolve(pageUrl, assetUrl)).pathname,
+ fileName = path.resolve(dirName, rootRelativePath.substr(1));
+ if (fileName in clientsByFileName) {
+ clientsByFileName[fileName].push(client);
+ } else {
+ clientsByFileName[fileName] = [client];
+ fs.watchFile(fileName, function (currStat, prevStat) {
+ if (currStat.mtime.getTime() !== prevStat.mtime.getTime()) {
+ clientsByFileName[fileName].forEach(function (client) {
+ var relativeUrl = buildRelativeUrl('file://' + client.baseDir,
+ 'file://' + fileName);
+ client.emit('change', relativeUrl);
+ });
+ }
+ });
+ }
+ });
+ }).on('disconnect', function () {
+ Object.keys(clientsByFileName).forEach(function (fileName) {
+ var clients = clientsByFileName[fileName],
+ clientIndex = clients.indexOf(client);
+ if (clientIndex !== -1) {
+ clients.splice(clientIndex, 1);
+ }
+ });
+ });
+ });
+};
View
@@ -8,7 +8,7 @@
"name": "Andreas Lind Petersen",
"email": "andreas@one.com"
}
- ]
+ ],
"name": "LiveStyle",
"description": "NodeJS middleware and binary for setting up a webserver that notifies the browser of CSS updates.",
"version": "0.0.0",
@@ -20,6 +20,14 @@
"engines": {
"node": ">= 0.4.0"
},
- "dependencies": {},
+ "dependencies": {
+ "express": "= 2.5.2",
+ "optimist": "= 0.3.0",
+ "socket.io": "= 0.8.7",
+ "socket.io-client": "= 0.8.7"
+ },
+ "directories": {
+ "bin": "./bin"
+ },
"devDependencies": {}
}

0 comments on commit 7651c54

Please sign in to comment.