Example #1
0
function runServer(
  options, /* {[]string projectRoot, bool web} */
  readyCallback
) {
  var app = connect()
    .use(loadRawBody)
    .use(openStackFrameInEditor)
    .use(getDevToolsLauncher(options))
    .use(statusPageMiddleware)
    .use(getFlowTypeCheckMiddleware(options))
    .use(getAppMiddleware(options));

  options.projectRoots.forEach(function(root) {
    app.use(connect.static(root));
  });

  app.use(connect.logger())
    .use(connect.compress())
    .use(connect.errorHandler());

  return http.createServer(app).listen(options.port, '::', readyCallback);
}
Example #2
0
    grunt.registerTask('runserver', 'Start the development server.', function(port) {
        this.async();
        port = port || 8000;

        connect()
            .use(connect.static('src'))
            .use(connect.directory('src', {icons: true}))
            .use('/js/vendor', connect.static('bower_components'))
            .use('/js/vendor', connect.directory('bower_components', {icons: true}))
            .use(connect.logger())
            .listen(port)
            .on('listening', function() {
                grunt.log.writeln('Starting static web server on port ' + port + '.');
            })
            .on('error', function(err) {
                if (err.code === 'EADDRINUSE') {
                    grunt.fatal('Port ' + port + ' is already in use by another process.');
                } else {
                    grunt.fatal(err);
                }
            });
    });
Example #3
0
app.createServer = function( ignore_plugin_list ) {
    
    ignore_plugin_list = ignore_plugin_list || [];

    var server = connect().use(connect.logger('dev'))
        .use(connect.static(relativePath + "/public"))
        // .use( sass.middleware({
        //           src: relativePath + "/sass"
        //         , dest: relativePath + '/public/css'
        //         , debug: true
        //       })) 
        .use(callbackServer);

    function callbackServer(req, res){      
        
        app.render( req.url , function( content ) {
            // Send response to client
            res.end( content );
        }, ignore_plugin_list );
    }

    // start server listen
    var myServer = http.createServer(server).listen(config.SERVER_PORT);

    // start socket
    io = io.listen(myServer);
    io.sockets.on('connection', function (socket) {});
    // reduce logging
    io.set('log level', 1);

    // start watch files
    app.startWatch();

    // open the page in browser
    app.openBrowser(null, function() {
        sh.echo( '✔ http://localhost:3000/index.html'.green );
    });

};
Example #4
0
function startServer(root, cb) {
    var devApp, devServer, devAddress, devHost, url, log=gutil.log, colors=gutil.colors;

    devApp = connect();
    if(cfg.server.log) {
        devApp.use(connect.logger(cfg.server.log===true ? 'dev' : cfg.server.log));
    }
    devApp.use(connect.static(root));

    devServer = http.createServer(devApp).listen(cfg.server.port, cfg.server.host||undefined);

    devServer.on('error', function(error) {
        log(colors.underline(colors.red('ERROR'))+' Unable to start server!');
        cb(error);
    });

    devServer.on('listening', function() {
        devAddress = devServer.address();
        devHost = devAddress.address === '0.0.0.0' ? 'localhost' : devAddress.address;
        url = 'http://' + devHost + ':' + devAddress.port + join('/', cfg.indexFile);

        log('');
        log('Started dev server at '+colors.magenta(url));
        var openByDefault = cfg.server.openByDefault;
        if(gutil.env.open || (openByDefault && gutil.env.open !== false)) {
            log('Opening dev server URL in browser');
            if(openByDefault) {
                log(colors.gray('(Run with --no-open to prevent automatically opening URL)'));
            }
            // Open the URL in the browser at this point.
            open(url);
        } else if(!openByDefault) {
            log(colors.gray('(Run with --open to automatically open URL on startup)'));
        }
        log('');
        cb();
    });
}
  grunt.registerTask('staticserver', 'Start a static web server.', function() {
    // Get values from config, or use defaults.
    var port = grunt.config('server.port') || 8000;
    var base = path.resolve(grunt.config('server.base') || '.');

    var middleware = [
      // Serve static files.
      connect.static(base),
      // Make empty directories browsable. (overkill?)
      connect.directory(base)
    ];

    // If --debug was specified, enable logging.
    if (grunt.option('debug')) {
      connect.logger.format('grunt', ('[D] server :method :url :status ' +
        ':res[content-length] - :response-time ms').magenta);
      middleware.unshift(connect.logger('grunt'));
    }

    // Start server.
    grunt.log.writeln('Starting static web server on port ' + port + '.');
    connect.apply(null, middleware).listen(port);
  });
Example #6
0
gulp.task('serve', ['build:examples'], function (cb) {
  var connectRoute = require('connect-route');
  var fs = require('fs');
  var data = fs.readFileSync('./examples/data/names-small.json', 'utf8');

  var app = connect()
    .use(connect.logger('dev'))
    .use(connect.static('./examples'))
    .use(connect.static('./public'))
    .use(connect.static('./dist'))
    .use(connectRoute(function (router) {
      router.get('/data', function (req, res) {
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(data));
      });
    }));

    http.createServer(app)
    .listen(CONFIG.port, function () {
      console.log('React Table example served up at', CONFIG.port);
    })
    .on('close', cb);
});
Example #7
0
function runServer(
  options,
  readyCallback
) {
  var app = connect()
    .use(loadRawBody)
    .use(openStackFrameInEditor)
    .use(getDevToolsLauncher(options))
    .use(statusPageMiddleware)
    // Temporarily disable flow check until it's more stable
    //.use(getFlowTypeCheckMiddleware(options))
    .use(getAppMiddleware(options));

  options.projectRoots.forEach(function(root) {
    app.use(connect.static(root));
  });

  app.use(connect.logger())
    .use(connect.compress())
    .use(connect.errorHandler());

  return http.createServer(app).listen(options.port, '::', readyCallback);
}
Example #8
0
// add logging token for current angle.
connect.logger.token('angle', function(request, response){ 
  var newangle = URL.parse(request.url).pathname.replace(/\D/,'') ;
    return "\x1b[33m "+ CURRENT_ANGLE +"\u00B0 \x1b[39m\u25B7" + (angleIsValid(newangle)?"\x1b[32m ":"\x1b[31m ") + (newangle||CURRENT_ANGLE) +"\u00B0 \x1b[39m" ;
})

var loggingOptions = { 
  immediate: true
, format: "\x1b[3m:remote-addr:\x1b[39m:angle :url" 
} ;

// listen for requests.
connect.createServer(
  connect.favicon()
  , connect.logger(loggingOptions)
  , function(request, response) { 
  
      var angle = URL.parse(request.url).pathname.replace(/\D/,'') ; // needs parse
        
      if (angleIsValid(angle)) { 
        log(angle, CURRENT_ANGLE) ;
        CURRENT_ANGLE = angle ; //  set current value
      } else {
        LOG_VERBOSE && log(request.socket.remoteAddress, request.url, angle, CURRENT_ANGLE) ;    
      }
        
      response.writeHead(200, {
        'Content-type': 'text/plain'
      });
      response.write(CURRENT_ANGLE+"\n") ;
/* Copyright (c) 2010-2014 Richard Rodger, MIT License */
'use strict'

var Connect = require('connect')
var Seneca = require('../..')

var si = Seneca()
si.use('echo')

Connect()
  .use(Connect.logger())
  .use(Connect.json())
  .use(si.export('web'))
  .listen(3000)

  // curl -H "Content-Type:application/json" -d '{"a":1}' http://localhost:3000/echo
Example #10
0
passport.serializeUser(function (user, done) {
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});

//Evetually we'll want to use templates to generate static versions of html files
//For now we just serve the mockups
app.use(connect.favicon("public/favicon.ico"));
//app.use(connect.static("public"));
app.use(connect.logger('tiny', {stream:{write:function (str) {
    console.info(str);
}}}));
app.use(function (req, res, next) {
    //We create an objParams object to hold parsed params
    req.objParams = req.objParams || {};
    next();
});
app.use(express.cookieParser());
app.use(express.bodyParser());

var MongoStore = require('connect-mongo')(express);
app.use(express.session({store:new MongoStore({db:"boxy"}), secret:"secreterthansecret"}));

app.use(passport.initialize());
app.use(passport.session());
//app.use(function (req, res, next) {
Example #11
0
/**
 * Module dependencies
 */

var connect = require('connect'),
	users = require('./users');

/**
 * Create server
 */

var server = connect(
connect.logger('dev'),
connect.bodyParser(),
connect.cookieParser(),
connect.session({
	secret: 'my app secret'
}),

function returning_user(req, res, next) {
	if ('/' == req.url && req.session.logged_in) {
		res.writeHead(200, {
			'Content-Type': 'text/html'
		});
		res.end('Welcome back, <b>' + req.session.name + '</b>. ' +
			'<a href="/logout">Logout</a>');
	} else {
		next();
	}
},
Example #12
0
function runServer(
  args: Args,
  config: ConfigT,
  // FIXME: this is weird design. The top-level should pass down a custom
  // reporter rather than passing it up as argument to an event.
  startedCallback: (reporter: Reporter) => mixed,
  readyCallback: (reporter: Reporter) => mixed,
) {
  var wsProxy = null;
  var ms = null;
  const packagerServer = getPackagerServer(args, config);
  startedCallback(packagerServer._reporter);

  const app = connect()
    .use(loadRawBodyMiddleware)
    .use(connect.compress())
    .use(
      getDevToolsMiddleware(args, () => wsProxy && wsProxy.isChromeConnected()),
    )
    .use(getDevToolsMiddleware(args, () => ms && ms.isChromeConnected()))
    .use(openStackFrameInEditorMiddleware(args))
    .use(copyToClipBoardMiddleware)
    .use(statusPageMiddleware)
    .use(systraceProfileMiddleware)
    .use(indexPageMiddleware)
    .use(packagerServer.processRequest.bind(packagerServer));

  args.projectRoots.forEach(root => app.use(connect.static(root)));

  app.use(connect.logger()).use(connect.errorHandler());

  if (args.https && (!args.key || !args.cert)) {
    throw new Error('Cannot use https without specifying key and cert options');
  }

  const serverInstance = args.https
    ? https.createServer(
        {
          key: fs.readFileSync(args.key),
          cert: fs.readFileSync(args.cert),
        },
        app,
      )
    : http.createServer(app);

  serverInstance.listen(args.port, args.host, 511, function() {
    attachHMRServer({
      httpServer: serverInstance,
      path: '/hot',
      packagerServer,
    });

    wsProxy = webSocketProxy.attachToServer(serverInstance, '/debugger-proxy');
    ms = messageSocket.attachToServer(serverInstance, '/message');
    readyCallback(packagerServer._reporter);
  });
  // Disable any kind of automatic timeout behavior for incoming
  // requests in case it takes the packager more than the default
  // timeout of 120 seconds to respond to a request.
  serverInstance.timeout = 0;
}
Example #13
0
require.paths.unshift("/usr/local/lib/node");

var connect      = require('connect');
//var form         = require('connect-form');
var main         = require('./endpoints/main');
var matches      = require('./endpoints/matches');
var games        = require('./endpoints/games');
var sampledata   = require('./endpoints/sampledata');


var server = connect.createServer(
	//form({ keepExtensions: false }),
	connect.logger({ buffer: true })
);

var vhost = connect.vhost('gunslinger', server);

server.use("/www", connect.staticProvider(__dirname + '/www'));
server.use("/www/resources/css", connect.staticProvider(__dirname + '/www/resources/css'));
server.use("/www/resources/imgs", connect.staticProvider(__dirname + '/www/resources/imgs'));
server.use("/www/resources/js", connect.staticProvider(__dirname + '/www/resources/js'));
server.use("/www/resources/templates", connect.staticProvider(__dirname + '/www/resources/templates'));

server.use("/sampledata/", connect.router(sampledata.endpoints));
server.use("/games/", connect.router(games.endpoints));
server.use("/matches/", connect.router(matches.endpoints));


server.use(main.defaultResponse);
server.use(main.renderResponse);
Example #14
0
var connect = require ('connect');
var http = require ('http');

var app = connect ()
    .use (connect.favicon ())
    .use (connect.logger ())
    .use (connect.static (__dirname + '/public'), {redirect:true})
    .use (function (req, res){
        res.end ('Hello world!');
    });



http.createServer (app).listen (9000);
Example #15
0
var connect = require('connect');
var url = require('url');
var proxy = require('proxy-middleware');

var port = 8080;

var proxyOptions = url.parse('http://blockexplorer.com');
proxyOptions.route = '/blockexplorer';

connect()
.use(proxyOptions)
.use(connect.logger('dev'))
.use(connect.static(__dirname)).listen(port);

console.log('Server started listening on port ' + port);
Example #16
0
 *
 * i.e. npm install connect
 *
 * @author dan@pupi.us (Daniel Pupius)
 */

var dys = require('dys');
var connect = require('connect');

new dys.Server(4103, '127.0.0.1').
    // Adds a response time header.  curl -I http://localhost:4103
    addConnectMiddleware(connect.responseTime()).
    
    // Logs each request to the console.  See dys.RequestLogModule for
    // a utility that logs to a file rather than spamming the console.
    addConnectMiddleware(connect.logger()).
    
    // Serves a favicon, but as noted below has limitations with 'dys'.
    addConnectMiddleware(connect.favicon()).
    
    // Add a simple action that serves at the root. 
    addAction('/', new dys.SimpleAction(200, '<h1>Connect Test</h1>')).
    
    // Currently, interceptors are only run for paths that match an existing
    // action, this has some nice properties, but is in contrast to the connect
    // model so may need changing.
    // For now we need to register a catch all action and manually 404 if an
    // interceptor doesn't handle the request.
    addAction('/*', new dys.SimpleAction(404, '<h1>Not Found</h1>')).
    
    // Start up the server.
Example #17
0
/* Module dependecies */
var connect = require("connect"),
      users = require("./users"), /* User authentication list provided by users.json */
      RedisStore = require("connect-redis")(connect); /* Mantains the user session although the active service shutdown */
var server = connect(
    connect.logger("dev"),
    connect.bodyParser(),
    connect.cookieParser(),
    connect.session({ store: new RedisStore, secret: "my app secret" }),
    function (req, res, next) {
        if ("/" == req.url && req.session.logged_in) {
            res.writeHead(200, {  "Content-Type": "text/html" });
            res.end(
                "Welcome back, <b>" + req.session.name + "</b>. "
                + "<a href='/logout'>Logout</a>"
            );
        } else {
            next();
        }
    }, function (req, res, next) {
        if ("/" == req.url && "GET" == req.method) {
            res.writeHead(200, { "Content-Type": "text/html" });
            res.end([
                "<form action='/login' method='POST'>",
                " <fieldset>",
                "   <legend>Please log in</legend>",
                "   <p>User: <input type='text' name='user'></p>",
                "   <p>Password: <input type='password' name='password'></p>",
                "   <button>Submit</button>",
                " </fieldset>",
                "</form>"
Example #18
0
  grunt.registerHelper('server', function(opts, cb) {
    cb = cb || function() {};

    var middleware = [];

    // add the special livereload snippet injection middleware
    if ( opts.inject ) {
      middleware.push( grunt.helper('reload:inject', opts) );
    }

    middleware = middleware.concat([
      // also serve static files from the temp directory, and before the app
      // one (compiled assets takes precedence over same pathname within app/)
      connect.static(path.join(opts.base, '../temp')),
      // Serve static files.
      connect.static(opts.base),
      // Make empty directories browsable.
      connect.directory(opts.base),
      // Serve the livereload.js script
      connect.static(path.join(__dirname, 'livereload')),
      // To deal with errors, 404 and alike.
      grunt.helper('server:errorHandler', opts),
      // Connect error handler (for better looking error pages)
      connect.errorHandler()
    ]);

    // the connect logger format if --debug was specified. Get values from
    // config or use defaults.
    var format = grunt.config('server.logformat') || (
      '[D] server :method :url :status ' +
      ':res[content-length] - :response-time ms'
    );

    // If --debug was specified, enable logging.
    if (grunt.option('debug')) {
      connect.logger.format('yeoman', format.magenta);
      middleware.unshift(connect.logger('yeoman'));
    }

    return connect.apply(null, middleware)
      .on('error', function( err ) {
        if ( err.code === 'EADDRINUSE' ) {
          return this.listen(0); // 0 means random port
        }

        // not an EADDRINUSE error, buble up the error
        cb(err);
      })
      .listen(opts.port, function(err) {
        var port = this.address().port;

        // Start server.
        grunt.log
          .subhead( 'Starting static web server on port '.yellow + String( port ).red )
          .writeln( '  - ' + path.resolve(opts.base) )
          .writeln('I\'ll also watch your files for changes, recompile if neccessary and live reload the page.')
          .writeln('Hit Ctrl+C to quit.');

        // create the reactor object
        grunt.helper('reload:reactor', {
          server: this,
          apiVersion: '1.7',
          host: opts.hostname,
          port: port
        });

        cb(null, port);
      });
  });
Example #19
0
function boot(port) {
	var sessionStore;		// will hold instance of the DB session storage class

	loadCore();				// load enabled core modules that are not deferred
	Rax.emit('coreLoaded'); // the earliest signal that modules can react to

	// shortcuts for boot messaging
	info = Rax.logging.info;
	warn = Rax.logging.warn;
	error = Rax.logging.error;

	// begin the boot process
	Rax.log(('[Rax] Core modules loaded').cyan);
	Rax.log(('[Rax] Booting...').cyan);

	info('Loading addon modules (not deferred)...');
	loadAddons();

	Rax.emit('addonsLoaded');

	// spin up the server
	info('Starting server...');
	Rax.server = connect.createServer();

	// connect various middleware
	// check: use static file server?
	if (cfg.USE_STATIC_FILESERVER) {
		info('Enabling static server @ ' + Rax.root + '/static');
		Rax.server.use(connect.static(Rax.root + '/static'));
	}

	// serve theme's static files
	Rax.server.use(connect.static(Rax.root, { maxAge: 1000 })); // @TODO enforce theme/module asset pathed from Rax CWD root?

	// register other helper middleware
	Rax.server.use(connect.favicon());	// provide favicon
	Rax.server.use(connect.query());	// parse query string into req obj

	if (cfg.ENABLE_REQUEST_LOGGING) {
		Rax.server.use(connect.logger());
	}

	// this returns a constructor for Rax's DB session store that connect's own session middleware will utilize
	sessionStore = new RaxStore(connect);	

	// session middleware (@TODO this should be optional, not ALL sites need session-tracking)
	Rax.server.use(connect.cookieParser());
	Rax.server.use(connect.session({
		'secret': 'RaxOnRaxOnRax',	// @TODO replace with session secret through admin dash/db cfg
		'store': new sessionStore({ 'db': 'sessions' }),
		'cookie': { 
			'maxAge': 60000 * 30 // idle sessions are good for 30 minutes
		}
	}));

	// @DEV user/session test middleware
	//Rax.server.use(Rax.middleware.checkSessionUser());
	Rax.server.use(function (req, res, next) {
		// @TODO put these in the pipeline instead ???
		Rax.active.req = req;
		Rax.active.res = res;
		// setup pipeline here? Rax.pipeline.init();
		
		// if session exists, see if a user is associated
		if (req.session && req.session.user && req.session.user !== 'anonymous') {
			Rax.user.get({ 'name': req.session.user }, function (err, user) {
				Rax.active.user = user;
				next();
			});
		} else {
			Rax.active.user = 'anon'; // @TODO provide anonymous user shell
			next();
		}
	});

	// lastly, connect router & the routes map
	Rax.server.use(connect.bodyParser()); // needed for forms processing
	Rax.server.use(Rax.router(core.routes));

	// listen!
	Rax.server.listen(port);

	// after bootstrap is done, save a private reference to the server and remove it from the public app object
	// so that it can't be damaged by rogue modules etc
	core.server = Rax.server;
	delete Rax.server;

	// bootstrap complete, safe for other modules to init
	Rax.emit('init');
	Rax.logging.c('[Rax] Booting complete. Rax is listening on ' + port + '...');
	Rax.logging.c('[Rax] Active theme = ' + Rax.active.theme.name);
}
Example #20
0
	function startServer() {
		
		var d10Server = connect().use(connect.favicon('../views/10er10.com/favicon.ico'));
		if ( !config.production ) {
			d10Server.use(connect.logger());
		}

		if ( config.gzipContentEncoding ) {
            var compressFilter = function(req, res){
              var type = res.getHeader('Content-Type') || '';
              return type.match(/css|text|javascript|json|x-font-ttf/);
            };
            d10Server.use(connect.compress({filter: compressFilter}));
		}
		stack.forEach(function(mw) { d10Server.use(mw); });


		var invitesServer = connect()
			.use(connect.logger())
			.use(contextMiddleware)
			.use(invitesLangMiddleWare)
			.use(connect.router(staticInvites))
			.use(connect.router(invitesRouter.api))
            .use(
			function (request,response) {
				response.writeHead(404,{"Content-Type": "text/plain"});
				response.end("The page does not exist");
			}
            )
        ;
		

		var globalSrv = connect()
			// 10er10 vhosts
			.use(connect.vhost(config.invites.domain,invitesServer))
		// 	defaultServer
			.use(d10Server)
		;
		var nodeHTTPServer = globalSrv.listen(config.port);
        var wsServer = new webSocketServer(nodeHTTPServer, d10Server);
		d10Server.on("clientError",function() {
			console.log("CLIENT ERROR");
			console.log(arguments);
		});
/*
		d10Server.on("error",function() {
			console.log("SERVER ERROR");
			console.log(arguments);
		});
		
		globalSrv.on("error",function() {
			console.log("SERVER ERROR");
			console.log(arguments);
		});
		globalSrv.on("clientError",function() {
			console.log("CLIENT ERROR");
			console.log(arguments);
		});
		*/
		console.log("Production mode ? ",config.production);
        console.log("Server listening on port", config.port);
	};
Example #21
0
app.configure(function() {
	app.use(connect.logger({ format: ':req[x-real-ip]\t:status\t:method\t:url\t' }));
	app.use(assets);
	app.use(connect.staticProvider(__dirname + '/public'));
});
Example #22
0
Server.prototype.start = function () {
    var self = this;
    var connect = require("connect");
    var url = require("url");
    var websocket = require("websocket");

    // Fire up a Haxe compiler server, ignoring all output. It's fine if this command fails, the
    // build will fallback to not using a compiler server
    spawn("haxe", ["--wait", HAXE_COMPILER_PORT], {stdio: "ignore"});

    // Start a static HTTP server
    var host = "0.0.0.0";
    var staticServer = connect()
        .use(function (req, res, next) {
            var parsed = url.parse(req.url, true);
            if (parsed.pathname == "/_api") {
                // Handle API requests
                req.setEncoding("utf8");
                req.on("data", function (chunk) {
                    self._onAPIMessage(chunk)
                    .then(function (result) {
                        res.end(JSON.stringify({result: result}));
                    })
                    .catch(function (error) {
                        res.end(JSON.stringify({error: error}));
                    });
                });

            } else {
                if (parsed.query.v) {
                    // Forever-cache assets
                    var expires = new Date(Date.now() + 1000*60*60*24*365*25);
                    res.setHeader("Expires", expires.toUTCString());
                    res.setHeader("Cache-Control", "max-age=315360000");
                }
                next();
            }
        })
        .use(connect.logger("tiny"))
        .use(connect.compress())
        .use(connect.static("build/web"))
        .listen(HTTP_PORT, host);
    console.log("Serving on http://localhost:%s", HTTP_PORT);

    this._wsServer = new websocket.server({
        httpServer: staticServer,
        autoAcceptConnections: true,
    });

    this._wsServer.on("connect", function (connection) {
        connection.on("message", function (message) {
            if (message.type == "utf8") {
                self._onMessage(message.utf8Data);
            }
        });
    });

    var net = require("net");
    this._connections = [];
    this._socketServer = net.createServer(function (connection) {
        self._connections.push(connection);
        connection.on("end", function () {
            self._connections.splice(self._connections.indexOf(connection, 1));
        });
        connection.on("data", function (data) {
            data = data.toString();
            if (data == "<policy-file-request/>\0") {
                // Handle Flash socket policy requests
                connection.end(
                    '<?xml version="1.0"?>' +
                    '<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">' +
                    '<cross-domain-policy>' +
                        '<allow-access-from domain="*" to-ports="'+SOCKET_PORT+'" />' +
                    '</cross-domain-policy>');
            } else {
                self._onMessage(data);
            }
        });
    });
    this._socketServer.listen(SOCKET_PORT, host);

    var watch = require("watch");
    var crypto = require("crypto");
    watch.createMonitor("assets", {interval: 200}, function (monitor) {
        monitor.on("changed", function (file) {
            console.log("Asset changed: " + file);
            var output = "build/web/"+file;
            if (fs.existsSync(output)) {
                var contents = fs.readFileSync(file);
                fs.writeFileSync(output, contents);
                self.broadcast("file_changed", {
                    name: path.relative("assets", file),
                    md5: crypto.createHash("md5").update(contents).digest("hex"),
                });
            }
        });
    });
};
Example #23
0
// wiki server
//

var connect = require('connect'),
    fs = require('fs'),
    sharejs = require('share').server;

// use the "use" call to set handlers (see below) instead of default.
//
var server = connect();

// log all requests
//
server.use(connect.logger());

// if the path begins with '/wiki', then serve the wiki page.
//
var wikiContent = fs.readFileSync('public/wiki.html');
server.use('/wiki', function(request, response, next) {
  response.end(wikiContent);

  // we _don't_ want to pass off handling to the "next" handler.
  //
  //next();
});

// default to serving "static" pages
//
server.use(connect.static(__dirname + '/public'));

// default to no database
Example #24
0
myWebServer.prototype.Init = function( _option )
{
	var self = this;

	self._option = _option;	//console.log('_option :', _option);

	/*
	*/
	var connect = gmConnect();
	self.connect = connect;

	connect.use( gmConnect.query() );
	connect.use( gmConnect.basicAuth('digest') );//connect.use( gmConnect.basicAuth('basic') );
	connect.use( gmConnect.favicon(self._option.basedir+'/images/favicon.ico') );
	connect.use( gmConnect.logger('dev') );
	connect.use( gmConnect.bodyParser({uploadDir:self._option.uploadbasedir, defer:true}) );
	connect.use( gmConnect.cookieParser() );
	connect.use( gmConnect.cookieSession( {secret:'some secret'/*, cookie: { maxAge: 60000 1min. }*/ }) );
	connect.use( function( _req, _res ) {
		return self._onWebServerRequest(_req, _res);
	});
	connect.use( gmConnect.errorHandler({message:true}) );

	/*
	*/
	var server = gmHttp.createServer(connect);
	/*
	var option = {
		key : gmFs.readFileSync('keyfile.pem'),
		cert : gmFs.readFileSync('certfile.pem'),
		//pfx : gmFs.readFileSync('pfxfile.pfx')
	}
	var server = gmHttps.createServer(option, connect);
	*/

	self.server = server;

	//server.on( 'request', _onWebServerRequest );
	server.on( 'connection', function() {
		console.log('Connection On');
	});

	server.on( 'close', function() { 
		console.log('WebServer Close On');		
	});

	server.on( 'checkContinue', function() { 
		console.log('WebServer _oncheckContinue On');		
	});

	server.listen( self._option.port, self._option.ipaddr, function() {
		return self._callbackWebServerListen();
	});

	/*
	*/
	var wsio = new gmWsIO();
	self.wsio = wsio;

	wsio.Listen( server );

	/*
	*/ 
	var webservice = new gmWebService();
	self.webservice = webservice;

	webservice.createSocket();
}
Example #25
0
const Koa = require('koa');
const connect = require('connect');
const c2k = require('..');

const app = new Koa();
app.use(c2k(connect.logger('dev')));
app.use(c2k(connect.directory(__dirname)));
app.use(c2k(connect.static(__dirname)));

app.use((ctx, next) => {
  ctx.body = 'koa';
  next();
});

app.listen(3000);
Example #26
0
var connect = require('connect')
  , request = require('request')
  , gm = require('gm')
  , fs = require('fs')
  , qs = require('querystring')
  , path = require('path')
  , util = require('./util')
  , server = connect();

server.use(function(req, res, next) {
  if (req.url == '/favicon.ico') return res.end();
  next();
});

server.use(connect.logger('dev'));

server.use(function(req, res, next) {
  req.query = qs.parse(req._parsedUrl.query);
  next();
});

server.use(function(req, res, next) {
  res.setHeader('Cache-Control', 'public, max-age=3600');
  next();
});

var images = {}
  , processing = {};

server.use(function(req, res) {
  var u = req.query.u // URL of the image
Example #27
0
         res.end("Not allowed");

      next(); // let the static server do the rest
   });
}

// set you cache maximum age, in milisecconds.
// if you don't use cache break use a smaller value
var oneMonth = 1000 * 60 * 60 * 24 * 30;

// start the server
var server = connect.createServer(
   // good ol'apache like logging
   // you can customize how the log looks: 
   // http://senchalabs.github.com/connect/middleware-logger.html
   connect.logger(),

   // call to trigger routes
   connect.router(routes),

   // set to ./ to find the boilerplate files
   // change if you have an htdocs dir or similar
   // maxAge is set to one month
   connect.static(__dirname+'/htdocs', {maxAge: oneMonth})
);

// bind the server to a port, choose your port:
server.listen(1111); // 80 is the default web port and 443 for TLS

// socket.io 
var socket = io.listen(server); 
Example #28
0
/**
 * Module dependencies.
 */

var connect = require('connect');

// $ curl http://localhost:3000/

// custom format string

connect.createServer(
    connect.logger(':method :url - :res[content-type]')
  , function(req, res){
    res.statusCode = 500;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Internal Server Error');
  }
).listen(3000);

// $ curl http://localhost:3001/
// $ curl http://localhost:3001/302
// $ curl http://localhost:3001/404
// $ curl http://localhost:3001/500

connect()
  .use(connect.logger('dev'))
  .use('/connect', connect.static(__dirname + '/lib'))
  .use('/connect', connect.directory(__dirname + '/lib'))
  .use(function(req, res, next){
    switch (req.url) {
Example #29
0
// node modules
var connect = require("connect");        // connect middleware
var cradle = require('cradle');          // noSQL database

// application modules
var UserManager = require('./js/user/UserManager.js');




var DEBUG = true;
var indexPage = null;

var server = connect.createServer(
  connect.logger("*** :status   :date - :url"),
  connect.favicon(__dirname + '/static/favicon.ico'),
  connect.cookieParser(),
  connect.session({secret:'some secret String'})
);


var dbNamespace = 'library_';
var dbProvider  = new(cradle.Connection)();
var db      = dbProvider.database(dbNamespace + 'db');




// ****************************
// **  dispatching requests  **
Example #30
0
var connect = require('connect'),
    http = require('http');

connect()
    .use(connect.logger(':method\: :url'))
    .use(connect.static('json'))
    .use(function(req, res){
       res.end('hello world\n');
    })
    .listen(3000);