Saturday, August 30, 2014

Node.js custom module express http server routing response file with simple chat using socket.io

appInclude.js

var fs = require("fs");
var url = require("url");

exports.createApp = function(express){
    var options = {
       
    };

    var app = express();
    app.get('/', function(req, res){
        var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
        console.log('Request from %s', ip);
       
        res.send('Welcome to NodeJS Express Server.');
    });
    app.get('/*', function(req, res){
        console.log('Request url is ' + req.originalUrl);
       
        var uri = url.parse(req.url);
        console.log('pathname: ' + uri.pathname);
       
        if(uri.pathname.length > 0){
            //hello.txt and more file
            var fname = uri.pathname.substring(1);
            fs.exists(fname, function(exists){
                if(exists){
                    var html = fs.readFileSync(fname);
                    res.writeHead(200, {'Content-Type': 'text/html'});
                    res.end(html);
                }else{
                    res.writeHead(404);
                    res.end("FileNotFound");
                }
            });
        }else{
            res.writeHead(404);
            res.end("PageNotFound");
        }
    });
    console.log(__dirname);
    app.use(express.static(__dirname));
    return app;
};

 
app.js

var sys = require("sys");
var express = require("express");
var include = require("./appInclude");

var app = include.createApp(express);
var server = app.listen(80, function() {
    console.log('Listening on port %d', server.address().port);
});

//npm install socket.io --msvs_version=2012
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
    console.log('Client connected...');
    socket.on('join', function (data) {
        socket.nickname = data.name;
        console.log('nickname is ' + data.name);       
    });
    socket.on('messages', function (data) {
        console.log(data);
        socket.broadcast.emit('messages', data);
    });
});

No comments: