Example #1
1
            return
        }
        resp.end(data)
    })
}

function isEditable(req){

}

function server(req, resp) {
    var pathname = filePathForReq(req)
    var ext = path.extname(pathname)
    if (['.js', '.html', '.css'].indexOf(ext) !== -1){
        fs.stat(pathname, function(err, stat){
            if (err){
                proxyRequest(req, resp)
            }else{
                serveFromFs(req, resp)
            }
        })
    }else{
        req.pipe(request(req.url)).pipe(resp)
    }
}

http.createServer(server).listen(8081)
https.createServer(server).listen(8081)


console.log('Server listening on 8081')
Example #2
0
http.createServer(function (req, res) {

    //w.info('got request '+req.url);

    var parsed = url.parse(req.url, true);

    if (parsed.pathname=='/info')
    {
        var params = parsed.query;

        var uid = params.uid ? params.uid : 0;        // default to userid 0
        var lim = params.lim ? params.lim : 100;
        var off = params.off ? params.off : 0;
       
        s="web_face: request : uid="+uid+" lim="+lim+" off="+off;
        // w.info(s);

        var qry = {};
        qry.offset=off;
        qry.limit=lim;
        qry.attr_name='userid';
        qry.attr_val=parseInt(uid);

        qry.responseq = 'web_data';

        qry.jobid = jid = u.suniq();
        qry.tsstart = Date.now();

        pillfetch.push(qry);

        jobs[jid] = {"qry":qry, "res":res};

        return;
    }

    res.writeHead(404);
    res.end();

}).listen(8500);
Example #3
0
var http = require("http");
var url = require("url");
var db = require("./mongotest");
console.dir("db -> " + db);
var port = 4444;
http.createServer(function(request, response) {
	var parsedUrl = url.parse(request.url, true);
  	var queryAsObject = parsedUrl.query;

	console.log("query: " + JSON.stringify(queryAsObject));
	response.writeHead(200, {"Content-Type": "text/html"});
	db.getUsers(function (err, data) {
		console.log("err: " + err);
		console.log("users: " + data);
		response.write(JSON.stringify(data));
		response.end();		
	} );
	console.log("Served!");
}).listen(4444);

console.log("listening on port: " + port);

//goto http://port-4444.jg8cina5by0kke29dqvxym5uuneo2yb9mpx60ahfmi7tx1or.box.codeanywhere.com/
//httpserverrequestpost.js

var http = require('http');
var querystring = require('querystring');
var util = require('util');

http.createServer(function(req, res) {
  var post = '';

  req.on('data', function(chunk) {
    post += chunk;
  });

  req.on('end', function() {
    post = querystring.parse(post);
    res.end(util.inspect(post));
  });

}).listen(3000);
Example #5
0
      console.error(err);
    }
    res.statusCode = 404;
    res.end('no such location');
  });
};

var pingHandler = function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('Pong!');
  res.end();
};

var middleware = route.comp([route.wrap(config.web.path, githubHandler), route.wrap('/ping', pingHandler)]);

var server = http.createServer(middleware);

var bot = new Eris(config.discord.token, {
  autoReconnect: true,
  disableEveryone: true,
  messageLimit: 10,
  sequencerWait: 100,
  disableEvents: {
    CHANNEL_CREATE: true,
    CHANNEL_DELETE: true,
    CHANNEL_UPDATE: true,
    GUILD_BAN_ADD: true,
    GUILD_BAN_REMOVE: true,
    GUILD_CREATE: true,
    GUILD_DELETE: true,
    GUILD_MEMBER_ADD: true,
Example #6
0
// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

Example #7
0
var server = http.createServer(
    function( request, response ){
    	console.log("JSON" + JSON.parse(request.url));
        var origin = (request.headers.origin || "*");

        if (request.method.toUpperCase() === "OPTIONS"){

            response.writeHead(
                "204",
                "No Content",
                {
                    "access-control-allow-origin": origin,
                    "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
                    "access-control-allow-headers": "content-type, accept",
                    "access-control-max-age": 10, // Seconds.
                    "content-length": 0
                }
            );

            return( response.end() );


        }

        var requestBodyBuffer = [];

        request.on(
            "data",
            function( chunk ){

                requestBodyBuffer.push( chunk );

            }
        );

        request.on(
            "end",
            function(){

                // Flatten our body buffer to get the request content.
                var requestBody = requestBodyBuffer.join( "" );

                // Create a response body to echo back the incoming
                // request.
                var responseBody = (
                    "Thank You For The Cross-Domain AJAX Request:\n\n" +
                    "Method: " + request.method + "\n\n" +
                    requestBody
                );
                console.log(request.method);
                console.log(JSON.parse(requestBodyBuffer).temp);
                	//http://www.bennadel.com/blog/2327-Cross-Origin-Resource-Sharing-CORS-AJAX-Requests-Between-jQuery-And-Node-js.htm);
                // Send the headers back. Notice that even though we
                // had our OPTIONS request at the top, we still need
                // echo back the ORIGIN in order for the request to
                // be processed on the client.
                response.writeHead(
                    "200",
                    "OK",
                    {
                        "access-control-allow-origin": origin,
                        "content-type": "text/plain",
                        "content-length": responseBody.length
                    }
                );

                // Close out the response.
                return( response.end( responseBody ) );

            }
        );


    }
);
Example #8
0
var http = require('http');

var server = http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('handled by child\n');
});

process.on('message', function (msg, httpServer) {
   if (msg === 'server') {
      httpServer.on('connection', function (socket) {
          server.emit('connection', socket);
      });
   }
});
Example #9
0
var http = require('http');
var fs = require('fs');
var connect = require('connect');

var server = http.createServer(
connect()
.use(connect.static('app'))
.use(connect.directory('app'))
);

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

server.listen(666);
Example #10
0
//In terminal - run: 

//npm install  - to download the necessary modules.
//node server.js - to run the server file in node.

var express = require('express'); //connect to the express module(external located in node_modules folder after npm install)
var http = require('http'); //connect to the http module (native to node)
var socketio = require('socket.io'); //connect to the socket.io module, this allows us to use websockets - so we can stream real time data to the server and clients.

var app = express(); //instantiate object of express as app

var server = http.createServer(app); //create our webserver using http, but pass it our express application this allows express to handle traffic and websockets to work through http
var io = socketio.listen(server); //create our io object which has access to the server & express.
var port = 8080; //set our port


app.use(express.static(__dirname+'/public')); //allow us to serve up the public folder for html files

server.listen(port);//start listening for traffic on our port

console.log("Listening on Port "+port+", press control-C to quit");


//socket event listener.
//this function sits and listens websocket traffic
//when it gets traffics it calls a function which it passes the socket
//for every socket event this gets called.
io.sockets.on('connection', function(socket){
	
	socket.emit('news', {hello: 'world'}); //we send off a hello event for our connection.
Example #11
0
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World\n');
  res.write('ohora World\n');
  res.end();
}).listen(8881, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8881/');
Example #12
0
var http = require('http'),
 csv = require('fast-csv');
var fs = require('fs');
var urlResource = require('url');
var portNumber = process.env.PORT || 5000,
    jsforce = require('jsforce');
console.log(portNumber);


http.createServer(function(req,resp){			   	
			resp.writeHead(200, {'Content-Type': 'text/plain'});
   		   
		   resp.end('Hello World\n');

}).listen(portNumber)
   .on('listening', function(){
      console.log('I am listening!');
   }).
   on('connection', function(){
               console.log('Hi a new connection received!');
   })
   .on('end', function(){
     console.log('I am stupid!');
   });
var through = require('through2');
var http = require('http');

var server = http.createServer(function(req, res) {
	if (req.method === "POST") {
		req.pipe(through(function(buff, _, next) {
			this.push(buff.toString().toUpperCase());
			next();
		})).pipe(res);
	} else
		res.send("Send me a POST\n");
});

server.listen(parseInt(process.argv[2]));
Example #14
0
var express = require("express");           // web framework external module
var io      = require("socket.io");         // web socket external module
var easyrtc = require("easyrtc");           // EasyRTC external module

// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var app = express();

function requireHTTPS(req, res, next) {
  var secure = req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === "https";
  var local = (/^localhost/).test(req.get('host'));
  if (!secure && !local) {
    return res.redirect('https://' + req.get('host') + req.url);
  }
  next();
}
app.use(requireHTTPS);

app.configure(function() {
  app.use(express.static(__dirname + "/static/"));
});

// Start Express http server on port 8080
var port = Number(process.env.PORT || 8080);
var webServer = http.createServer(app).listen(port);

// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer, {"log level":1});

// Start EasyRTC server
var rtc = easyrtc.listen(app, socketServer);
#!/usr/bin/env node

const PORT = 5000;

var http = require('http'),
    connect = require('connect'),
    favicon = require('serve-favicon'),
    serve_static = require('serve-static'),
    logger = require('morgan'),

    app = connect()
        .use(logger('dev'))
        .use(favicon('./www/assets/images/iojs.ico'))
        .use(serve_static('./www', {index: ['index.html']}));

http.createServer(app).listen(PORT, function() {
    console.log('Server listening on port ' + PORT);
});
let server = http.createServer((req,res)=>{

  console.log('req.method',req.method);

  console.log('req.url',req.url);

  // let pathName = url.parse(req.url).pathname;
  // console.log('pathname',pathName);

  let reqURL = req.url.match(/[^/]+/g) || [];

  console.log('reqURL',reqURL);

  let path = reqURL[0];
  let urlData = reqURL[1];

  switch(path) {

      case 'math' : res.write(math(urlData));
                    // console.log('math');
                    res.end('\n');break;

      case 'age' : res.write(age(urlData));
                    // console.log('age');
                    res.end('\n');break;

      case 'analyzer' : res.write(analyzer(urlData));
                    // console.log('analyzer');
                    res.end('\n');break;

      case 'generator' : res.write(generator(urlData));
                    // console.log('gene');
                    res.end('\n');break;

      case 'magicball' : res.write(magicball(urlData));
                    console.log('magicball');
                    res.end('\n');break;

      case 'spellcheck' : res.write(spellcheck(urlData));
                    console.log('spellcheck');
                    res.end('\n');break;

      case 'dictionary' : res.write(`\n\nDefinition : ${dictionary(urlData)}`);
                    console.log('dictionary');
                    res.end('\n\n');break;

      default     : res.statusCode = 404;
                    res.end('Use routes /spellcheck, /math, /age, /analyzer, /magicball, /gene .eg /math/2+2\n');
                    break;
  }

  res.end();

}).listen(PORT,err => {
Example #17
0
var http = require('http');

const PORT = 8081; // Non-standard HTTP port
//const PORT 80; // Standard HTTP port

function handleRequest(request, response) {
  console.log(request.headers);
  response.end('It Works!! Path Hit: ' + request.url + '\n');
}

var server = http.createServer(handleRequest);
server.listen(PORT, function () {
  console.log("Server listening on: http://localhost:%s", PORT);
});
Example #18
0
const server = http.createServer((req, res) => {
  if (req.url === '/events') {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
      'Access-Control-Allow-Origin': '*'
    });
    clients.add(res);

    const t = setInterval(() => {
      res.write('data: PING\n\n');
    }, 5000);

    res.socket.on('close', () => {
      clients.delete(res);
    });
  } else if (req.url.startsWith('/fire')) {
    const query = url.parse(req.url, true).query;
    for (const c of clients) {
      c.write(`data: ${query.id}\n\n`);
    }
    res.writeHead(200, {
      'Access-Control-Allow-Origin': '*'
    });
    res.end();
  } else {
    res.writeHead(404);
    res.end();
  }
});
Example #19
0
    {
        secret: process.env.COOKIE_SECRET || "Superdupersecret"
    }));

app.configure('development', 'production', function() {
    app.use(express.csrf());
    app.use(function(req, res, next) {
        res.cookie('XSRF-TOKEN', req.csrfToken());
        next();
    });
});

app.use(passport.initialize());
app.use(passport.session());

passport.use(User.localStrategy);
//passport.use(User.twitterStrategy());  // Comment out this line if you don't want to enable login via Twitter
//passport.use(User.facebookStrategy()); // Comment out this line if you don't want to enable login via Facebook
//passport.use(User.googleStrategy());   // Comment out this line if you don't want to enable login via Google
//passport.use(User.linkedInStrategy()); // Comment out this line if you don't want to enable login via LinkedIn

passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);

require('./server/routes.js')(app);

app.set('port', process.env.PORT || 8000);
http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});
Example #20
0
var http = require('http');

http.createServer(function(req, resp) {
  var pinNumber = 1;
  var state = '';
  
  resp.writeHead(200, {'Content-Type': 'text/html'});
  resp.write("hello world");
  resp.end();
}).listen(8080);

var http       = require('http'),
    express    = require('express'),
    bodyParser = require ('body-parser'),
    morgan     = require ('morgan'),
    faye       = require('faye');


var bayeux = new faye.NodeAdapter({
  mount:    '/faye',
  timeout:  45
});


var app = express();
var server = http.createServer(app);

bayeux.attach(server);

app.use(morgan());
app.use(bodyParser());
app.use(express.static(__dirname + '/public'));

app.post('/message', function(req, res) {
  bayeux.getClient().publish('/channel', {text: req.body.message});
  res.send(200);
});

var port = process.env.port || 3000;
server.listen(port);
console.log('Server up and listening on port ' + port);
Example #22
0
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');
var socketio = require('socket.io');

// 웹 서버를 생성합니다.
var server = http.createServer(function (req, res) {
    // HTMLPage.html 파일을 읽습니다.
    fs.readFile('HTMLPage.html', function (error, data) {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(data);
    });
}).listen(52273, function () {
    console.log('Server running at http://127.0.0.1:52273');
});

// 소켓 서버를 생성 및 실행합니다.
var io = socketio.listen(server);
io.sockets.on('connection', function (socket) {

});
Example #23
0
const PORT = 8886;
const http = require('http'),
	fs   = require('fs'),//文件模块
	url  = require('url'),
	path = require('path'),
	util = require('./util');
// var [http,fs,url,path,mime] =  ['http','fs','url','path','./mime'].map((x) => require(x))

http.createServer(tellme)
.listen(PORT);

console.log('Server start')
console.log('Server runing: '+ getIPAdress() + ':' + PORT);



//请求进来时候执行的代码
function tellme(req,res){
 	req.setEncoding('utf-8');// 以utf-8编码来接收请求

    var pathname = url.parse(req.url).pathname
    // .replace(/^\/.+?\/$/,function(a){return a + 'index.html'}); //如果是文件夹结尾,跟上index.html

    var	fileUrl = (__dirname + pathname).replace(/\\/g,'\/') ;

    console.log('--')
    console.log('---fileUrl----' + fileUrl);
    // console.log('---pathname---' + pathname)

    if(pathname === '\/'){
    	//目录
Example #24
0
  publicPath: webpackConfig.output.publicPath,
  stats: {
    colors: true
  },
  reporter: function (data) {
    // @see https://github.com/webpack/webpack/blob/324d309107f00cfc38ec727521563d309339b2ec/lib/Stats.js#L790
    // Accepted values: none, errors-only, minimal, normal, verbose
    const options = WebpackStats.presetToOptions('minimal');

    options.timings = true;

    const output = data.stats.toString(options);

    process.stdout.write('\n');
    process.stdout.write(output);
    process.stdout.write('\n\n');
  }
}));

// Add the dev proxies in the express App
Shared.addProxies(app);

app.use(express.static(webpackConfig.output.path));

const server = http.createServer(app);

server.listen(process.env.PORT || 3000, function () {
  console.log('Listening on port', server.address().port);
  progressBar = new ProgressBar('[:bar] :percent :etas', { total: 50 });
});
Example #25
0
					if(err) {
						send404(response);
					} else {
						cache[absPath] = data;
						sendFile(response, absPath, data);
					}
				});
			} else {
				send404(response);
			}
		});
	}
}

var server = http.createServer(function(request, response) {
	var filePath = false;
	if(request.url == '/') {
		filePath = 'public/index.html';
	} else {
		filePath = 'public' + request.url;
	}
	var absPath = './' + filePath;
	serveStatic(response, cache, absPath);
});

server.listen(3000, function() {
	console.log('Server listening on port 3000.');
});

var chatServer = require('./lib/chat_server');
chatServer.listen(server);
"use strict"

var http = require("http");

http.createServer(function(request, response) {
    // Handle find the Fibonacci with random number
    var numRandom = getRandomInt(1, 50),
        numsFibonacciSeries = exportNumberFibonacciSeries(numRandom);

    // Handle show the results
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("The first " + numRandom + " numbers in the Fibonacci series: " + numsFibonacciSeries);
    response.end();
}).listen(3000);

/*
 * Export n number of Fibonacci series (n = nRandom)
 * @param int nRandom
 * @return string strNumsFibonacciSeries
 */
function exportNumberFibonacciSeries(nRandom) {
    if (nRandom == 1) return "0";
    if (nRandom == 2) return "0 1";

    var arrNumsFibonacciSeries = [0, 1],
        strNumsFibonacciSeries = "0 1 ",
        i = 2;

    while (i < nRandom) {
        // Find next number in series
        var nextNumber = arrNumsFibonacciSeries[i - 1] + arrNumsFibonacciSeries[i - 2];
Example #27
0
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(
function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);

});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
Example #28
0
		if(err) return console.log(err, obj);
		if(!Session.byUserID.hasOwnProperty(obj.targetUserID)) return;
		var user = Session.byUserID[obj.targetUserID].user;
		if(user.info.subscriber) return;
		user.info.subscriber = true;
		Group.users.sendEvent("/user/person/", user.info);
		user.sendEvent("/user/subscription/", {expireTime: obj.expireTime});
	});
});


var listener = httpx.listener(root, fileHandler);
if(config.server.secureURL) {
	http.createServer(function(req, res) {
		res.writeHead(301, {
			"Location": config.server.secureURL+req.url,
		});
		res.end();
	}).listen(config.server.port, config.server.host);
	util.log("Forwarding HTTP to HTTPS");
} else {
	http.createServer(listener).listen(config.server.port, config.server.host);
}

try {
	var certOpts = {
		key: fs.readFileSync(__dirname+"/../server.key"),
		cert: fs.readFileSync(__dirname+"/../server.crt"),
		honorCipherOrder: true,
	};
	https.createServer(certOpts, listener).listen(config.server.securePort, config.server.host);
} catch(e) {
Example #29
0
function launch(conn){

  var port = process.env.GATEBLU_PORT || 8888;

  function updateIp(){
    sendLanIp(conn.uuid, conn.token, port, conn);
    setTimeout(updateIp, 1000 * 3600);
  }

  function gatewayMiddleware(req, res, next){
    res.locals({
      token: conn.token,
      uuid: conn.uuid,
      conn: conn
    });
    next();
  }

  var app = express();
  var parser = express.json();

  // all environments
  app.set('port', port);
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  //app.use(express.json());
  app.use(express.urlencoded());
  app.use(express.methodOverride());
  app.use(gatewayMiddleware);
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));


  // development only
  if ('development' == app.get('env')) {
    app.use(express.errorHandler());
  }

  app.get('/', routes.index);
  app.get('/plugins', pluginRoute.plugins);
  app.get('/subdevices', pluginRoute.subdevices);
  app.post('/subdevices', parser, pluginRoute.createSubdevice);
  app.put('/subdevices', parser, pluginRoute.updateSubdevice);
  app.delete('/subdevices/:name', pluginRoute.deleteSubdevice);
  app.post('/subdevices/:name/reload', pluginRoute.reloadSubdevice);
  app.post('/plugins/:name', pluginRoute.installPlugin);
  app.delete('/plugins/:name', pluginRoute.uninstallPlugin);
  app.put('/plugins/:name', pluginRoute.updatePlugin);

  var server = http.createServer(app);
  server.on('error', function(err){
    console.log('error launching webser...', err);
    process.exit(1);
  });
  server.listen(app.get('port'), function(){
    console.log('Skynet Gateway webserver listening at http://localhost:' + app.get('port'));
  });

  try{
    //optional dependency for gateblue that can broadcast its presence locally.
    var mdns = require('mdns');
    var ad = mdns.createAdvertisement(mdns.tcp('gateblu'), parseInt(port, 10));
    ad.start();
  }catch(mdnsE){
    //console.log('mdns', mdnsE);
  }

  return conn;
}
Example #30
0
 var https = require('https');
 var url = require('url');
 var StringDecoder = require('string_decoder').StringDecoder;
 var config = require('./config');
 var fs = require('fs');
 var handlers = require('./handlers');
 var helpers = require('./helpers');
 var path = require('path');


// Instantiate the server module object
var server = {};

 // Instantiate the HTTP server
server.httpServer = http.createServer(function(req,res){
   server.unifiedServer(req,res);
 });

 // Instantiate the HTTPS server
server.httpsServerOptions = {
   'key': fs.readFileSync(path.join(__dirname,'/../https/key.pem')),
   'cert': fs.readFileSync(path.join(__dirname,'/../https/cert.pem'))
 };
 server.httpsServer = https.createServer(server.httpsServerOptions,function(req,res){
   server.unifiedServer(req,res);
 });

 // All the server logic for both the http and https server
server.unifiedServer = function(req,res){

   // Parse the url