Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

socket.io + node cross domain ... possible?

socket.io + node cross domain ... possible?

Problem

So, is possible to watchFile a file that is not in your own domain cross-domain. For example something like this:

var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    fs = require('fs'),
    homeFile = __dirname + '/home',
    jsonFeed = 'https://www.example.com/data';
app.listen(8080, 'mixserver.dev');


function handler(req, res) {
    fs.readFile(homeFile, function(err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading home');
        }

        res.writeHead(200);
        res.end(data);
    });
}

io.sockets.on('connection', function(socket) {
    fs.watchFile(jsonFeed, function (curr, prev) {
        var t = prev.mtime.getTime();

        fs.readFile(jsonFeed, function(err, data) {
            if (err) throw err;

            var data = JSON.parse(data);
            socket.emit('feed', data);
        });
    });
});
Problem courtesy of: Darkagelink

Solution

There are no Cross Domain issues from node.js. The only time cross domain matters is when making a connection from the browser. The problem here is with watchFile. I don't believe you can watch a URL. You can only watch a local file.

Instead of fs.watchFile, you will want to use setInterval (or setTimeout with some magic sauce) to periodically pull the jsonFeed. I also recommend this library for doing web requests: https://npmjs.org/package/request

You could rewrite that last handler like this:

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

    setInterval( function() {
        request( jsonFeed, function (error, response, body) {

            if (error) {
                // handle error
                return;
            }

            var data = JSON.parse(body);
            socket.emit('feed', data);
        } );
    }, 5000 );
});
Solution courtesy of: Anthony Hildoer

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

socket.io + node cross domain ... possible?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×