Example #1
0
var connect   = require("connect"),
    fs        = require("fs"),
    mustache  = require("mustache");
var dfdf;

connect(
  connect.static(__dirname + "/public"),
  connect.bodyParser(),
  function(req, res) {

    if (req.method == "POST") {

      var userName = {
          firstName: req.body.firstName,
          lastName: req.body.lastName
        };

      console.log(userName);

      // create and open the stream
      var tmplFile = fs.createReadStream(__dirname + "/server/templates/template1.html",
                                        {encoding: "utf8"});

      var template = "";
      var html;

      tmplFile.on("data", function(data) {
          template += data;
      });

      tmplFile.on("end", function() {
Example #2
0
#!/usr/bin/env node

var os = require('os'),
    connect = require('connect');

var port = 8888;
var webServer = connect();
webServer
    .use(connect.logger())
    .use(connect.favicon('static/favicon.ico'))
    .use(connect.static('static'))
    .use(connect.static('external'))
    .use(connect.static('lib'))
    .use(connect.bodyParser());

console.log("=======================================");
console.log("Listening on http://" + os.hostname() + ":" + port + "/");
console.log("=======================================");
webServer.listen(port);
Example #3
0
// demo演示了:
// 1. 'connect ' middleware framework 的使用, http://www.senchalabs.org/connect/  or  https://github.com/senchalabs/Connect 。
// 2. 理解中间件的含义: 看注释。
var connect = require('connect')
    , http = require('http');
var app = connect();
// Middleware: 以流式方式依次处理请求,然后响应客户端或是让下一个中间件继续处理。即use函数的callback参数相当于 ‘response’event的回调函数
app.use(connect.favicon())
    .use(connect.logger('dev'))
    .use(connect.static('public'))
    .use(connect.directory('public'))
    .use(connect.cookieParser())
    .use(connect.bodyParser())
    .use(connect.session({ secret: 'my secret here' }))
    .use(function(req, res) {
        res.end('viewing user ' +  (req.body.user && req.body.user.name) );
    });
app.listen(9001);

Example #4
0
gulp.task('static-server', function (next) {
  var connect = require('connect');
  var server = connect();
  server.use(connect.static(paths.dist)).listen(process.env.PORT || 3002, next);
});
Example #5
0
var path = require('path');
var rt = require('connect-rt');
var Loader = require('loader');
var connect = require('connect');
var render = require('connect-render');
var urlrouter = require('urlrouter');

var config = require('./config');
var routes = require('./routes');

var PUBLIC_DIR = path.join(__dirname, 'public');

var app = connect();

app.use(rt({headerName: 'X-ReadTime'}));
app.use('/public', connect.static(PUBLIC_DIR));
app.use(function (req, res, next) {
  res.req = req;
  next();
});

//parse http get params
app.use(connect.query());

//parse http post body
app.use(connect.urlencoded());
app.use(connect.json({
  strict: true
}));

//parse cookie
Example #6
0
//@http://stackoverflow.com/questions/6084360/node-js-as-a-simple-web-serve   

console.log('Start connect at http://localhost:9000');

var connect = require('connect');
connect.createServer( connect.static(__dirname)).listen(9000);
Example #7
0
var connect = require("connect")
    , connect_router = require("connect_router")
    , _router = require("./router");

var httpServer = connect.createServer()
        .use(connect.logger({ immediate: true, format: 'dev' }))
        .use(connect.bodyParser())
        .use(connect.cookieParser())
        .use(connect.session({ secret: 'keyboard cat'}))
        .use(connect_router(_router.main))
        .use(connect.static(__dirname+"/Resource"))
        .use(connect.errorHandler( {statck:true,message:true,dump:true}))
        .listen(process.env.PORT, process.env.IP, function(){
            console.log("Run on Server...");
        });
Example #8
0
    makeServer : function( serverProps ) {
      var clients           = {},
          serverID          = global.interface.servers.length,
          root              = serverProps.directory,
          midiInit          = false,
          interfaceJS       = null,
          webserver         = null,
          serveInterfaceJS  = null,
          midiOut           = null,
          midiNumbers       = {
            "noteon"        : 0x90,
            "noteoff"       : 0x80,
            "cc"            : 0xB0,
            "programchange" : 0xC0,
          },
          server            = {
            shouldAppendID: false,
            shouldMonitor : false,
            clients       : clients,
            masterSocket  : null,
            livecode      : false,
            clientCount   : 0,
            serveInterfaceJS : function(req, res, next){
              //var ip = req.connection.remoteAddress;

            	req.uri = url.parse( req.url );
    
              var extension = req.uri.pathname.split('.').pop();
    
              if(extension == 'htm') {
                fetchingInterface = req.uri.pathname.slice(1);
              }
          
              var js = "__socketPort = " + server.webSocketPort + "; \n" + global.interface.interfaceJS;
          
            	if( req.uri.pathname === "/interface.js" ) {
            		res.writeHead( 200, {
            			'Content-Type': 'text/javascript',
            			'Content-Length': js.length
            		})
            		res.end( js );
    
            		return;
            	}
  
              next();
            },
          };

      global.interface.extend( server, serverProps );

      if(server.outputType === 'WebSocket') {
        server.master = null;
        server.listener = (server.webSocketMasterPort === WEBSOCKET_ADMIN_PORT) ? global.interface.websocketAdminIn : new ws.Server({ port:server.webSocketMasterPort });
        server.clients = clients
        console.log( 'LISTENING ON', server.listener.port ) 
        server.listener.on( 'connection', function (connectedSocket) {
          server.master = connectedSocket;
          console.log("MASTER IS CONNECTED") 
          server.master.ip = server.master._socket.remoteAddress;
                    
          server.master.on( 'message', function( obj ) {
            var args = JSON.parse( obj )
            global.interface.handleMsgToClients( server, args.address, args )
          });
      
        })
      }else if( server.outputType === 'OSC' ){
        server.oscOutput = new omgosc.UdpSender( server.oscOutputIP, server.oscOutputPort );
        
        if(global.interface.portsInUse.indexOf( server.oscInputPort ) === -1) {
          // don't open a new port if the admin port is the same as the desired input port
          server.oscInput = server.oscInputPort === OSC_ADMIN_PORT ?  global.interface.oscAdminIn : new omgosc.UdpReceiver( server.oscInputPort )
          global.interface.portsInUse.push( server.oscInputPort ); 
        }else{
          alert('there is already a service runnning on port ' + server.oscInputPort + '. please choose another port for osc input.');
          return;
        }        
      }else{
        if( !midiInit ) {
          midiOutput = new midi.output();
          midiOutput.openVirtualPort( "Interface.Server Output" );
          midiInit = true;
        }
      }

      if( global.interface.portsInUse.indexOf( server.webSocketPort ) === -1 ) {
        server.webSocket  = new ws.Server({ port:server.webSocketPort });
        global.interface.portsInUse.push( server.webSocketPort );
      }else{
        alert( 'there is already a service runnning on port ' + server.webSocketPort + '. please choose another socket port.' );
        if( server.oscInput !== null ) { 
          server.oscInput.close(); 
          global.interface.portsInUse.splice( global.interface.portsInUse.indexOf( server.oscInputPort ), 1 );
        }
        return;
      }

      if(global.interface.portsInUse.indexOf( server.webServerPort ) === -1) {
        if( server.livecode === true ) {
          server.webServer = connect()
            .use( server.serveInterfaceJS )
            .use( function(req, res) { res.end( global.interface.livecodePage ) })
            .listen( server.webServerPort );
          server.name = 'livecode';
        }else{
          server.webServer = connect()
            .use( connect.directory( server.directory, { hidden:true,icons:true } ) )
            .use( server.serveInterfaceJS )
            .use( connect.static( server.directory ) )
            .listen( server.webServerPort );
        }
        global.interface.portsInUse.push( server.webServerPort );
      }else{
        alert( 'there is already a service runnning on port ' + server.webServerPort + '. please choose another web server port.' );
    
        if( server.oscInput !== null ) { 
          server.oscInput.close();
          global.interface.portsInUse.splice( global.interface.portsInUse.indexOf( server.oscInputPort ), 1 );
        }
    
        if( server.webSocket !== null ) {
          global.interface.portsInUse.splice( global.interface.portsInUse.indexOf( server.webSocketPort ), 1 );
          server.webSocket.close();
        }
        return;
      }

      global.interface.createWebSocketListener( server );
      
      if(server.outputType === 'OSC') {
        server.oscInput.on('', function(args) {
          // console.log( 'MSG RECEVIED ' + args.path + ' : CLIENTS COUNT ' + server.clients.length )
          var split = args.path.split("/");          
          if(split[1] === 'clients') {
            var msg = {},
                clientNum = parseInt(split[2]),
                address = "/" + split.slice(3).join('/'),
                remote = null;
                        
            msg.address = address;
            msg.typetags = args.typetag;
            msg.parameters = args.params;
            msg.type = 'osc'
            
            for(var key in server.clients) {
              var client = server.clients[key];
              if( client.id === clientNum ) {
                remote = client;
                break;
              }
            }
    
            if(remote !== null)
              remote.send( JSON.stringify( msg ) );
          }else{
            for(var key in server.clients) {
              // console.log( 'CLIENT ' + key ) 
              var client = server.clients[key];
              client.send( JSON.stringify({ type:'osc', address:args.path, typetags:args.typetag, parameters:args.params }) );
            }
          }
        });
        server.oscOutput.send( '/serverCreated', 's', [ server.name ] ); 
      }else if( server.outputType === 'WebSocket' ) {
        if( server.master !== null ) { 
          this.connectMaster( server.master ) 
        }
      }

      global.interface.servers.push( server );
      
      return server;
    },
Example #9
0
var connect = require('connect');
var port = process.env.PORT || 5000;

connect.createServer(
    connect.static(__dirname)
).listen(port);

console.log("Server running on port :" + port);
gulp.task('server', ['build'], function (next) {
	var server = connect();
	server.use(connect.static(buildDir)).listen(port, next);
});
Example #11
0
/*
 * register error handler for uncaught exceptions
 */
process.on('uncaughtException', function (err) {
    errorlog.error(err.stack);
  });

var requestStream = Fs.createWriteStream(__dirname + '/log/requests.log', {
    flags: 'a',
    encoding: 'utf-8'
  });

var server = Connect.createServer(
  Connect.bodyParser(),
  Connect.static(__dirname + '/public'),
  RequestLogger({ log: log, logStream: requestStream }),
  Connect.errorHandler({showStack: true, dumpExceptions: true})
);

var context = {
  log: log,
  store: {
    parts: Store.createStore({ name: 'parts', log: log }),
    carts: Store.createStore({ name: 'carts', log: log }),
    templates: Store.createStore({ name: 'templates', log: log })
  }
};

(function initModules() {
    Fs.readdirSync(CONTROLLER_DIR).forEach(function (file) {
Example #12
0
//      overriding defaults from argv
//
var configDefaults = {
  docRoot : docRoot,
  port: 3000,
  hostname: 'localhost',
  verbose: false,
  logger: 'short'
};
var appConfig = delegate(configDefaults, argv);
var verbose = appConfig.verbose;

if(require.main === module){
  if("help" in argv){
    var helpStr = "Usage: node index.js [options]\n\n";
      helpStr += "Options:\n";
    Object.keys(configDefaults).forEach(function(name){
      helpStr += "  --"+name+ " "+ configDefaults[name] + "\n";
    });
    console.log(helpStr);
  } else {

    connect()
      .use(connect.static(appConfig.docRoot))
      .use(dirlisting(appConfig.docRoot))
      .listen(appConfig.port, appConfig.hostname);

  }
  console.log('serving on %s:%s; out of %', appConfig.hostname, appConfig.port, appConfig.docRoot);
}
Example #13
0
    resource.view.create({ path: __dirname + '/view' }, function(err, view) {
      if (err) {
        callback(err);
        return;
      }

      resource.http.app.use(resource.view.middle({ view: view, prefix: '/admin' }));

      //
      // Serve the /public/ admin folder
      //
      resource.http.app.use(connect.static(__dirname + '/public'));

      //
      // TODO: cleanup route handlers / make into common methods
      //

      resource.http.app.get('/admin', auth, function (req, res, next) {
        var _r = _resources();
        view.index.present({ resources: resource.resources }, function(err, str){
          res.end(str);
        });
      });

      resource.http.app.get('/admin/datasources/:datasource', auth, function (req, res, next) {
       resource.datasource.get(req.param('datasource'), function(err, result){
         view.datasource.present({ datasource: result }, function (err, str){
           res.end(str);
         });
       });
      });

      resource.http.app.get('/admin/resources/:resource', auth, function (req, res, next) {
        view.resource.present({
          resource: req.param('resource')
        }, function(err, str){
          res.end(str);
        });
      });

      resource.http.app.get('/admin/resources/:_resource/:_method', auth, function (req, res, next) {
        view.method.present({ resource: req.param('_resource'), method: req.param('_method') }, function(err, str){
          res.end(str);
        });
      });

      resource.http.app.post('/admin/resources/:_resource/:_method', auth, function (req, res, next) {

        var id = req.param('id'),
            data = req.resource.params;

        delete data._resource;
        delete data._method;

        view.method.present({
          resource: req.param('_resource'),
          method: req.param('_method'),
          data: data,
          action: 'post',
          id: id
        }, function(err, str){
          res.end(str);
        });


      });

      resource.http.app.get('/admin/resources/:_resource/:_method/:id', auth, function (req, res, next) {
        var _id = req.param('id');
        view.method.present({
          resource: req.param('_resource'),
          method: req.param('_method'),
          id: _id
        }, function(err, str){
          res.end(str);
        });
      });

      resource.http.app.post('/admin/resources/:_resource/:_method/:id', auth, function (req, res, next) {

        var data = req.resource.params;

        view.method.present({
          resource: req.param('_resource'),
          method: req.param('_method'),
          id: req.param('id'),
          data: data,
          request: req,
          response: res,
          action: 'post'
        }, function(err, str){
          res.end(str);
        });

      });

      callback(null, resource.http.server);

    });
Example #14
0
// setup mongodb vith mongoose
var models = require('./models');

// request handlers for messages api
var messageHandlers = require('./messageHandlers')(models.messages);

// messages api routing
server.get('/api/v1/messages/:id', 
  messageHandlers.getMessages);
server.get('/api/v1/messages', 
  messageHandlers.getMessages);
server.post('/api/v1/messages/:id', 
  ensureAuthenticated, messageHandlers.postMessage);
server.post('/api/v1/messages', 
  ensureAuthenticated, messageHandlers.postMessage);
server.del('/api/v1/messages/:id', 
  ensureAuthenticated, messageHandlers.deleteMessage);

// set up middleware and start server
var connect = require('connect');
connect()
  .use(connect.logger())
  .use(connect.cookieParser())
  .use(connect.session({ secret: 'saignwittis', key: 'sid' }))
  .use(passport.initialize())
  .use(passport.session())
  .use(connect.static(__dirname + '/../client/app'))
  .use(connect.compress())
  .use('/', function (req, res) { 
      server.server.emit('request', req, res);
  }).listen(3000);
Example #15
0
var http = require('http');
var request = require('request');
var ejs = require('ejs');
var connect = require('connect');
var fs = require('fs');

var layout = fs.readFileSync(__dirname + '/godspeed.html','utf8');
console.log('Loaded template: ' + layout);

var app = connect();
app.use(connect.static(__dirname + '/assets'));

// Listen for requests from web browsers
app.use(function(serverRequest, serverResponse) {

	//We received a request from a web browser
	console.log('Get request for ' + serverRequest.url);

	//Send status code and headers
	serverResponse.writeHead(200, {'Content-Type': 'text/html'});

	//Get the weatherfrom aeris
	request('http://api.aerisapi.com/batch?requests=/observations/oslo,norway,/observations/rio+de+janeiro,br,/observations/new+haven,ct&client_id=c6T7tvujoI7SgytJmNj7l&client_secret=Q5GRGQyhPn4Jd8Vp1a2hGgk6Y85Bew1pP6dIbsQW', 
			function(error, response, body) {

	var weather = JSON.parse(body);
    var windSpeed1 = weather.response.responses[0].response.ob.windKPH;
    var windDir1 = weather.response.responses[0].response.ob.windDirDEG;
    var windDir1a = weather.response.responses[0].response.ob.windDir;
    var windSpeed2 = weather.response.responses[1].response.ob.windKPH;
    var windDir2 = weather.response.responses[1].response.ob.windDirDEG;
Example #16
0
var connect = require("connect"),
    send = require("send"),
    formatDate = require("dateformat");

var cache = require("./cache")({
  "user-max-age": 1000 * 60 * 5, // five minutes
  "user-cache-size": 1 << 8, // 256
  "gist-max-age": 1000 * 60 * 5, // five minutes
  "gist-cache-size": 1 << 11, // 2048
  "file-max-size": 1 << 19, // 512K
  "file-cache-size": 1 << 27 // 128M
});

var server = connect()
    .use(connect.compress())
    .use(connect.static("static"));

// Gist Redirect
// e.g., /0123456789/
// e.g., /0123456789/d39b22ba1ca024287f98c221fd74f39a3f990cdf/
server.use(function(request, response, next) {
  var u = url.parse(request.url), r;
  if (!(r = /^\/((?:[0-9]+|[0-9a-f]{20})(?:\/[0-9a-f]{40})?)\/$/.exec(u.pathname))) return next();
  var id = r[1];
  response.statusCode = 301;
  response.setHeader("Location", "/" + id);
  response.end();
});

// Gist
// e.g., /0123456789
Example #17
0
gulp.task('server', function () {
    var app = connect().use(connect.static(root));

    http.createServer(app).listen(port);
    open(protocol + '://' + host + ':' + port);
});
Example #18
0
(function () {
  "use strict";

  require('bufferjs');

  try {
    require('./tcp-echo');
    require('./udp-echo');
  } catch(e) {
    console.warn("[TODO] switch tcp and udp ports for development");
  }

  var config = require('./config')
    , connect = require('connect')
    , btoa = require('btoa')
    , url = require('url')
    , server
    , echoServer
    , whatsmyip
    , sessions = {}
    ;

  // clear out sessions occasionally
  setInterval(function () {
    Object.keys(sessions).forEach(function (sessionToken) {
      var session = sessions[sessionToken];
      if (Date.now() - session.timestamp >= 10 * 60 * 1000) {
        delete sessions[sessionToken];
      }
    });
  }, 10 * 60 * 1000);

  function randomize() {
    return 0.5 - Math.random();
  }

  function newToken() {
    return btoa(String(Date.now()).split('').sort(randomize).join('')).substr(0,16);
  }

  var ipcheck = /^\/(whatsmy|my|check)?ip($|\?|\/|#)/
    ;

  function echo(req, res, next) {
    var urlObj = {}
      , params
      , sessionToken
      , session
      , resHeaders
      , resBody
      ;

    console.log('Echo Echo Echo...');

    if (/GET/i.exec(req.method) && '/' === req.url && !req.body || /assets/.exec(req.url)) {
      return next();
    }

    // If the user just wants the IP address
    if (ipcheck.exec(req.url)) {
      res.setHeader('Content-Type', 'text/plain');
      res.end(req.socket.remoteAddress);
      return;
    }

    //
    // Parse QUERY and BODY
    //
    urlObj = url.parse(req.url, true, true);
    console.log(urlObj);
    delete urlObj.search;
    urlObj.httpVersion = req.httpVersion;
    urlObj.method = req.method;
    urlObj.headers = req.headers;
    urlObj.trailers = req.trailers;

    urlObj.remoteAddress = req.socket.remoteAddress;
    urlObj.remotePort = req.socket.remotePort;

    params = (!(req.body instanceof Buffer) && 'object' === typeof req.body && req.body) || urlObj.query;
    if (params.rawResponse) {
      params.raw = req.body;
    } else if (params.rawBody) {
      params.body = req.body || urlObj.body;
    }

    /*
    console.log(req.connection === req.socket); // true
    console.log(req.connection === req.client); // true
    console.log(req.client === req.socket); // true
    */

    // how can we determine these?
    urlObj.protocol = req.protocol || 'http:';
    urlObj.host = req.headers.host;
    urlObj.hostname = urlObj.host.split(':')[0];
    urlObj.port = urlObj.host.split(':')[1];

    urlObj.href = url.format(urlObj);


    // TODO If not params load index.html, else echo

    //
    // Set RAW
    //
    if (params.raw) {
      // the connection is most likely keepalive
      // calling .end is not necessary?
      res.socket.write(params.raw);
      return;
    }


    //
    // Get Session
    //
    sessionToken = params.session || req.headers['X-Foobar3k-Session'] || newToken();
    session = { headers: [], resources: {} };
    session = sessions[sessionToken] = sessions[sessionToken] || session;
    session.timestamp = Date.now();
    urlObj.session = sessionToken;
    res.setHeader('X-Foobar3k-Session', sessionToken);



    // If the user wants to post a resource to get later
    // TODO test against pathname instead?
    if (params.pathname && /^\/meta\/?(\?.*)?$/.exec(req.url)) {
      res.setHeader('content-type', 'application/json');

      if (/GET|DELETE/.exec(req.method)) {
        if (/DELETE/.exec(req.method)) {
          delete session.resources[params.pathname];
        }
        res.end(JSON.stringify({
            "error": false
          , "errors": []
          , "success": true
          , "resources": session.resources
          , "status": "ok"
        }));
        return;
      }

      // TODO OPTIONS, HEAD

      session.resources[params.pathname] = params;
      res.setHeader('content-type', 'application/json');
      res.end(JSON.stringify({
          "error": false
        , "errors": []
        , "success": true
        , "resource": params
        , "status": "ok"
      }));

      return;
    }

    // If this is a resource that the user previously posted
    // give it back now
    // TODO normalize trailing '/'
    if (urlObj.pathname && session.resources[urlObj.pathname]) {
      params = session.resources[urlObj.pathname];
    }


    //
    // Set HEADERS
    //
    function setHeader(header) {
      var key = (header.split(':')[0]||'').trim()
        , val = (header.split(':')[1]||'').trim()
        ;

      if (val) {
        res.setHeader(key, val);
      } else {
        res.removeHeader(key, val);
      }
    }
    // for all requests with this session
    session.headers = params.defaultHeaders || session.headers;
    session.headers.forEach(setHeader);
    resHeaders = params.headers || [];
    resHeaders = Array.isArray(resHeaders) ? resHeaders : [resHeaders];
    resHeaders.forEach(setHeader);


    //
    // set STATUS
    //
    res.statusCode = params.status || res.statusCode;


    //
    // Set BODY
    //
    resBody = params.body || urlObj;
    /*
    if (/HEAD|OPTIONS/.exec(req.method)) {
      resBody = undefined;
    }
    */
    if (resBody === urlObj) {
      if (!res.getHeader('content-type')) {
        res.setHeader('content-type', 'application/json');
      }
      console.log('!rawBody', urlObj);
      res.end(JSON.stringify(urlObj, null, '  '));
    } else {
      console.log('rawBody');
      res.end(resBody);
    }
  }

  function bodySnatcher(req, res, next) {
    var data = []
      ;

    if (req.body || !(req.headers['transfer-encoding'] || req.headers['content-length'])) {
      console.log('No Body');
      return next();
    }

    req.on('data', function (chunk) {
      data.push(chunk);
    });

    req.on('end', function () {
      req.body = Buffer.concat(data);
      console.log('Has Body');
      next();
    });
  }

  server = connect.createServer(
      function (req, res, next) {
        console.log('Echo Blah');
        console.log(req.subdomains);
        next();
      }
    , connect.favicon()
    , connect.bodyParser()
    , bodySnatcher
    , echo
    , connect.static(__dirname + '/')
  );

  echoServer = connect.createServer(
      function (req, res, next) {
        console.log('Echo Server');
        next();
      }
    , connect.favicon()
    , connect.bodyParser()
    , bodySnatcher
    , echo
  );

  /*
    server.listen(config.port);
    console.log('Started on ' + config.port || 80);
  */

  whatsmyip = connect.createServer(function (req, res, next) {
    // yes, it's that simple
    res.setHeader('Content-Type', 'text/plain');
    res.end(req.socket.remoteAddress);
  });

  // TODO enhance vhost with regex checkin'
  var middleware
    ;

  middleware = [];

  // TODO inspect subdomains instead of using vhost a second time
  middleware = [
      connect.vhost('whatsmyip.*', whatsmyip)
    , connect.vhost('checkip.*', whatsmyip)
    , connect.vhost('myip.*', whatsmyip)
    , connect.vhost('ip.*', whatsmyip)
    , connect.vhost('*helloworld3000.*', server)
    , connect.vhost('*foobar3000.*', server)
    , connect.vhost('*', server)
  ];

  module.exports = connect.createServer.apply(connect, middleware);

  try {
    connect.createServer.apply(connect, middleware).listen(8080);
  } catch(e) {
    console.warn('[WARN] probably already bound on 8080');
  }
}());
Example #19
0
var connect = require('connect');

connect.createServer(
  connect.static('./public')
).listen(3000);
 it('allows static middleware to be chained after', function() {
     // Add a regular static middleware so that requests for .jsx
     // are properly handled.
     app.use(connect.static(path.join(__dirname, 'root')));
 });
Example #21
0
/*
 * Simple connect server for phantom.js
 * Adapted from twitter bootstrap server.
 */

var connect = require('connect')
  , http    = require('http')
  , fs      = require('fs')
  , path    = require('path')
  , app     = connect();

var pidFile = path.resolve(__dirname, './pid.txt');

app.use(connect.static(path.resolve(__dirname, '../')));

http.createServer(app).listen(8000, function () {
  fs.writeFileSync(pidFile, process.pid, 'utf-8');
});

Example #22
0
function thrust(ship, ts) {
  // generate a small thrust vector
  var t = new Vector(0.0, -0.05);
  // rotate thrust vector by player current heading
  t.rotate(ship.heading * Vectors.RAD);
  ship.vector.add(t);
}

function brake(ship, ts) {
  ship.vector = new Vector(0.0, 0.0);
}


var dial = function(current, change, limit) {
  var absolute = current + change;
  if(change < 0 && absolute < 0) // gone over
    return limit + absolute % limit;
  else if(change > 0 && absolute > limit)
    return absolute % limit
  else
    return absolute;
}


/*-----------------------------------------------
  Web Server
-----------------------------------------------*/
var server = connect.createServer();
server.use('/', connect.static(WEB_ROOT));
server.use('/javascripts/shared', connect.static(SHARED_ROOT));
server.listen(9595);
Example #23
0
var express = require('express'),
    report = require('./routes/report');
 
var app = express();
 
app.configure(function () {
    app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
});
 
app.get('/report', report.findAll);
//app.get('/report/:id', report.findById);
app.post('/report', report.addReport);
//app.put('/report/:id', report.updateWine);
//app.delete('/report/:id', report.deleteWine);
 
app.listen(3000);
console.log('Web service listening on port 3000...');

// Use Node.js as mini web server to display web page
// Ref: http://stackoverflow.com/questions/15231864/display-html-page-with-node-js
var connect = require('connect'),
    http = require('http');
connect()
   .use(connect.static('/home/tuanht/git/js-crawl'))
   .use(connect.directory('/home/tuanht/git/js-crawl'))
   .listen(8080);
console.log('Localhost: web server listening on port 8080...');
Example #24
0
var connect = require('connect'), 
    http = require('http'),
    app;

app = connect()
  .use(connect.static('app'))
  .use('/scripts/vendor/', connect.static('node_modules/requirejs/'))
  .use('/node_modules', connect.static('node_modules'));

http.createServer(app).listen(8080, function() {
  console.log('Running on http://localhost:8080');
});
Example #25
0
var connect = require('connect');
connect.createServer(
    connect.static("www")
).listen(8080);
console.log("server started at localhost:8080");
Example #26
0
nwAddon.initialize = function(){
    try {
        //Hold the node-webkit GUI
        this.gui = require("nw.gui");
        //Hold a copy of the filesystem
        this.fs = require("fs");
        //Hold a version of JSZip (from node.js)
        this.JSZip = require("jszip");
        //Hold a copy of the OS data
        this.os = require("os");
        
        //***HTML***//
        $("body").prepend("<input style=\"display: none;\" id=\"openFileDialog\" type=\"file\" accept=\".ge,.sb2\" />");
        
        //***LOCAL SERVER!***//
        //Hold a version of http
        var http = require("http");
        //Hold a version of Connect
        var connect = require('connect');
        try{
            http.createServer(connect().use(connect.static("./"))).listen(6564);
        }catch(e){
            console.log(e);
            console.warn("Something is using port [6564]. Relieve this port if you want to host GE files on your computer.");
        }
        
        //***WINDOW MENUS!***//
        var windowMenu = new this.gui.Menu({ type: 'menubar' });
        this.gui.Window.get().menu = windowMenu;
        
        var fileSubMenu = new this.gui.Menu();
        
        //SET SUB-MENUS!!
        fileSubMenu.append(new this.gui.MenuItem({ label: "New Project", click: function(e){
                if (window.confirm("Are you sure you want to make a new project?")) {
                    //Load up the default project
                    ge.io.loadProjectZipFromNodeFile("./create/editor/default.ge");
                }
            }
        }));
        fileSubMenu.append(new this.gui.MenuItem({ type: "separator" }));
        fileSubMenu.append(new this.gui.MenuItem({
                label: "Open...",
                click: function(e){
                        $("#openFileDialog").off("change").one("change", function(){
                            //Open it
                            ge.io.loadProjectZipFromNodeFile($(this).val());
                        }).click();
                }
        }));
        fileSubMenu.append(new this.gui.MenuItem({
                label: "Save",
                click: function(e){
                        saveProject();
                }
        }));
        fileSubMenu.append(new this.gui.MenuItem({
                label: "Save As...",
                click: function(e){
                        saveProjectAs();
                }
        }));
        fileSubMenu.append(new this.gui.MenuItem({ type: "separator" }));
        fileSubMenu.append(new this.gui.MenuItem({
                label: "Quit",
                click: function(e){
                        nwAddon.gui.Window.get().close();
                }
        }));
        
        //Set the menu of the window to our custom submenus (Mac OSX has needs to have File before required "Edit")
        if(this.os.platform() === "darwin"){
                this.gui.Window.get().menu.insert(new this.gui.MenuItem({ label: "File", submenu: fileSubMenu }), 1);
        }else{
                var finishedMenu = new this.gui.Menu({ type: "menubar" });
                finishedMenu.append(new this.gui.MenuItem({ label: "File", submenu: fileSubMenu }));
                
                this.gui.Window.get().menu = finishedMenu;
        }
        
        //***File Handling***//
        //If we were opened by a file, open the file (only the first one, though)
        if (this.gui.App.argv && this.gui.App.argv[0]) {
            //Open it
            ge.io.loadProjectZipFromNodeFile(this.gui.App.argv[0]);
        }else{
            //Load up the default project
            ge.io.loadProjectZipFromNodeFile("./create/editor/default.ge");
        }
        
        //***NW EVENTS***//
        //Listen to the window for closing; if there is an unsaved project, we should
        //ask the user if they want to save
        this.gui.Window.get().on("close", function(e){
            //CHECK FOR UNSAVED PROJECT!!
            ge.editor.parser.saveCurrentObjectInJSON();
            
            if (!Object.equals(ge.projectInfo.initialJSON, ge.projectInfo.json)) {
                if(window.confirm("Your project is unsaved!\nWould you like me to save it for you?"))
                {
                    saveProject();
                }
            }
            
            this.hide();
            //Shutdown
            this.close(true);
        });
        
    } catch(e) {
        console.log(e);
        console.warn("Not running in node-webkit, node-webkit features will be unavailable");
        
        nwAddon.usingnw = false;
    }
};
Example #27
0
var connect = require('connect');
var server = connect.createServer();
server.use(connect.static(__dirname + '/website'));
server.listen(3000);

server.use(function (req, res, next) {
    console.error( '%s %s ', req.method, req.url);
    next();
});

server.use(function (req, res, next) {
    if ('GET' == req.method && '/images' == req.url.substr(0, 7)) {
        // 托管图片
    } else {
        // 交给其他的中间件
        next();
    }
});

server.use(function (req, res, next) {
    //
    res.writeHead(404);
    res.end('Not Found');
});

  var patternprimer = function () {
    var done = this.async();
    var options = this.options();
    var data = this.data;

    // default settings, overwritten with user defined settings
    settings = {
      pattern_port: Array.isArray(data.ports) && data.ports[0] ? data.ports[0] : Array.isArray(options.ports) && options.ports[0] ? options.ports[0] : 7020,
      snapshot_port: Array.isArray(data.ports) && data.ports[1] ? data.ports[1] : Array.isArray(options.ports) && options.ports[1] ? options.ports[1] : 7040,
      wwwroot: data.wwwroot || options.wwwroot || 'public',
      src: data.src || options.src || 'public/patterns',
      dest: data.dest || options.dest || 'docs',
      snapshot: (data.snapshot !== undefined ? data.snapshot : (options.snapshot !== undefined ? options.snapshot : false)),
      index: data.index || options.index || null,
      css: data.css || options.css || ['global.css']
    };

    // local pattern folder (there are the html snapshots)
    var patternFolder = './' + settings.src;

    // our main function that starts the process
    var primer = function (cb) {
      readPatterns(patternFolder, cb);
    };

    // middleware to spit out 404 (in case a non existing ressource is request)
    // or to process the `non static` requests
    var middleware = function (req, resp) {
      if (req.url !== '/') {
        resp.writeHead(404, {
          'Content-Length': 0,
          'Content-Type': 'text/plain'
        });
        resp.end();
        return;
      }

      // 200, success, always
      resp.writeHead(200, {'Content-Type': 'text/html'});
      // run the primer with cb
      primer(resp.end.bind(resp));
    };

    // initialize the server with static routes & dynamic template middleware
    var liveServer = connect.createServer(
      connect.static(process.cwd() + '/' + settings.wwwroot),
      middleware
    );

    // initialize the static server pointing to your snapshots
    var snapshotServer = connect.createServer(connect.static(process.cwd() + '/' + settings.dest));

    // starts the live server
    var startLiveServer = function () {
      liveServer.listen(settings.pattern_port, function () {
        grunt.log.ok('You can now visit http://localhost:' + settings.pattern_port + '/ to see your patterns.');
      });
    };

    // starts the snapshot server
    var startSnapshotServer = function () {
      snapshotServer.listen(settings.snapshot_port, function () {
        grunt.log.ok('You can now visit http://localhost:' + settings.snapshot_port + '/ to see your snaphsot patterns.');
      });
    };

    // writes the task output to a file 
    var writeSnapshot = function () {
      primer(function (content) {
        var promises = [];
        // write the index file
        grunt.file.write('./' + settings.dest + '/index.html', content);
        // copy css files
        settings.css.forEach(function (file) {
          var deferred = Q.defer();
          promises.push(deferred.promise);
          if (file.search('http://') !== -1) {

            var data = '';
            http.get(file, function (res) {
              res.on('data', function(chunk) {
                data += chunk;
              });
              res.on('end', function () {
                grunt.file.write('./' + settings.dest + '/style.css', data);
                deferred.resolve();
              });
            })
            .on('err', deferred.reject);
          } else {
            grunt.file.copy('./' + settings.wwwroot + '/' + file, './' + settings.dest + '/' + file);
          }
        });

        grunt.log.ok('Stand-alone output can now be found in "' + settings.dest + '/"');
        grunt.event.emit('patternprimer:snapshot:written');
        if (promises.length === 0) {
          done();
        } else {
          Q.allSettled(promises).then(done);
        }
      });
    };

    // writes to file or starts a server,
    // depending on the given snapshot var
    if (!!settings.snapshot) {
      writeSnapshot();
    } else {
      startLiveServer();
      // only start snapshot server, if snapshots are available
      if (grunt.file.exists('./' + settings.dest + '/index.html')) {
        startSnapshotServer();
      }
    }

  };
Example #29
0
    getParams: function() {
      return req.query;
    }
  };

  var router = makeRouter(
    routes.getRoutes(app),
    routes.getNotFound(app)
  );

  router.go(app.getPath());
}

// Set up the application and run it
var server = connect()
  .use(connect.static(__dirname + '/build'))
  .use(connect.logger())
  .use(connect.cookieParser())
  .use(connect.cookieSession({
    secret: IRLMOJI_COOKIE_SECRET,
    cookie: {
      maxAge: 365 * 24 * 60 * 60 * 1000, // 1 year in seconds, doesn't work tho
      proxy: true
    }
  }))
  .use(fixConnectCookieSessionHandler)
  .use(guestHandler)
  .use(connect.csrf())
  .use(apiProxyHandler)
  .use(connect.urlencoded())
  .use(connect.query())
Example #30
0
var connect = require('connect'),
	socketPort = 4801,
	httpPort = 4800;

connect.createServer( connect.static(__dirname) ).listen(httpPort);

var engine = require("./node-core-audio").createNewAudioEngine();
var outputBuffer = [];

var io = require('socket.io').listen(socketPort);

var sockets = [];

io.sockets.on('connection', function (socket) {
	sockets.push( socket );
});

io.set( 'log level', 2 );

var options = {
	inputChannels: 1,
	framesPerBuffer: 4096,
}

engine.setOptions( options );

options = engine.options;

var totalSamples = 0;
var freq = 20000.0;