Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8411967
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T00:33:33+00:00 2026-06-10T00:33:33+00:00

I have this code in my server.js file at node.js: var app = require(‘http’).createServer(handler),

  • 0

I have this code in my server.js file at node.js:

var app = require('http').createServer(handler), io = require('socket.io').listen(app);
var xml2js = require('xml2js'), parser = new xml2js.Parser(), fs = require('fs');

// creating the server ( localhost:8000 )
app.listen(8000);

/**
 * Esta función es la que envía el archivo js necesario para la comunicación
 * push con sockets
 * 
 * @param req
 * @param res
 */
function handler(req, res) {
    Request = require('url').parse(req.url, true);
    site = Request.query.site;
    entity = Request.query.entity;
    id = Request.query.id;

    fs.readFile(__dirname + '/client.js', 'utf8', function(err, data) {
        if (err) {
            console.log(err);
            res.writeHead(500);
            return res.end('Error loading client.js');
        }
        var dataString = data.toString();
        dataString = dataString.replace('confSite', site);
        dataString = dataString.replace('confEntity', entity);
        dataString = dataString.replace('confId', id);
        res.writeHead(200, {
            'Content-Type' : 'text/javascript;charset=UTF-8'
        });
        res.end(dataString);
    });
};

var listeners = {};
var parsers = {};
var listenersAndSockets = {};
var socketsOnListeners = {};
var watchers = {};
/**
 * Esta función es la que enviará la información que se actualice a los
 * clientes. Escuchará un archivo xml el cual envará al cliente una vez que este
 * haya cambiado
 */
io.sockets.on('connection', function(socket) {
    socket.on ('connect', function() {
        console.log('conectado');
    });
    socket.on('setup', function(config) {
        console.log('setup');
        var site = config.site;
        var entity = config.entity;
        var id = config.id;
        var listenerName = '' + site + entity + id + '';
        watchers[listenerName] = site + '/' + '/' + entity + '/' + id + '.xml';
        socketsOnListeners[socket.id] = listenerName;
        if (typeof socketsOnListeners[listenerName] == 'undefined') {
            socketsOnListeners[listenerName] = {};
        }
        socketsOnListeners[listenerName][socket.id] = socket.id;
        if (typeof listeners[listenerName] == 'undefined') {
            parsers[listenerName] = new xml2js.Parser();
            fs.stat(watchers[listenerName], function(err, stats) {
                if (err) {
                    fs.writeFile(watchers[listenerName], '');
                }
            });
            listeners[listenerName] = function(curr, prev) {
                fs.readFile(watchers[listenerName], function(err, data) {
                    parsers[listenerName].parseString(data);
                });
            };
            fs.watch(watchers[listenerName], listeners[listenerName]);
        }
        parsers[listenerName].addListener('end', function(result,a) {
            socket.volatile.emit('notification', result);
        });
    });

    socket.on('disconnect', function() {
        delete socketsOnListeners[socketsOnListeners[socket.id]][socket.id];
        if (socketsOnListeners[socketsOnListeners[socket.id]].lenght == 0) {
            fs.unwatch(watchers[socketsOnListeners[socket.id]]);
            delete watchers[socketsOnListeners[socket.id]];
        }
        delete socketsOnListeners[socket.id];
    });
});

And in my test.html I have this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Prueba de Push</title>
</head>
<body>

    <div id="div1">Este es un texto de prueba</div>

    <script src="http://10.0.0.113:8000/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://10.0.0.113:8000/?site=levelup&entity=noticia&id=1"></script>

    <script>
        function test(data) {
            console.log(data);
            jQuery('#' + data.id).html(data.content);
        }
    </script>


</body>
</html>

Client.js is this:

var socket = io.connect('http://10.0.0.113:8000');
var config = {
    site : 'confSite',
    entity : 'confEntity',
    id : 'confId'
};

socket.emit("setup", config);
socket.on('reconnect', function() {
    socket.emit("setup", config);
});
// on every message recived we print the new datas inside the #container div
socket.on('notification', function(data) {
    _efbn(data.callback, window, data.response, data);
});

/**
 * Función que ejecuta una función por nombre. Puede usar namespaces
 * (algo.algo.algo.funct)
 * 
 * @see http://stackoverflow.com/questions/359788/javascript-function-name-as-a-string/359910#359910
 */
function _efbn(functionName, context) {
    var args = Array.prototype.slice.call(arguments);
    args = [ args[2], args[3] ]; // Fix para IE.
    var namespaces = functionName.split(".");
    var func = namespaces.pop();
    for ( var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }
    try {
        if (typeof context[func] == 'function') {
            return context[func].apply(this, args);
        }
    } catch (e) {
        console.log(e);
    }
    return null;
}

And in firefox, I’m receiving twice or more the notification when I modify the file on the server. Is there any way to prevent this? I have read something about groups at node.js… will that maybe help me?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T00:33:34+00:00Added an answer on June 10, 2026 at 12:33 am

    You start watching file in setup event. At client side setup event may be emited several times (reconnect event). For each watch call new listener will be added to file. You need to check is watch listener already exists on file (for this socket) before setup it. Also you need unwatch file after socket will be closed. Otherwise you will get a memory leak.

    UPDATE

    Also you need to move

    parser.addListener('end', function(result) {
        socket.volatile.emit('notification', result);
    });
    

    outside setup event.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code to download a file, but on sourceforge.net sever there is
I have this code for server code in c, under unix: /* A simple
I have this code to create a webapp in my server: import web urls
I used to have this code working with my Tomcat server: HttpRequestBase targetRequest =
I cannot access to server through RestClient. I have this code written in cURL
I have this mySQL code that connects to my server. It connects just fine:
I have this horribly stripped delphi code that basically login to server, save cookie
This is my server code I have a problem because my program freeze and
I have this code for uploading files on the server: <tr> <td> <form enctype=multipart/form-data
I have a node server and I want to add an external .js file

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.