Is there any “globals” function in Javascript which is similar to PHP globals that would apply in this example?
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
querystring = require('querystring');
app.listen(8000);
var content = '';
function handler(req, res) {
io.sockets.on('connection', function (socket) {
if(req.method == 'POST') {
var fullBody = '';
req.on('data', function(chunk) {
fullBody += chunk.toString();
});
req.on('end', function() {
var decodedBody = querystring.parse(fullBody);
console.log(decodedBody);
socket.emit('user-aaa5c8bbffe4db9', fullBody);
});
}
});
fs.readFile(__dirname + '/index.html',
function(err, data) {
if(err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
I wrote a PHP app but I want to have notifications through socket.io but I don’t want to rewrite the app for Node.js (yet) so I setup a Node server which the PHP will send a POST to and then the server will send the notification via Socket.io. I’ve tested the server with basic scripts and they do work. I’ve also tried moving the “io.sockets.on(‘connection’, function (socket) {” inside the IF statement:
req.on('end', function() {
var decodedBody = querystring.parse(fullBody);
console.log(decodedBody);
io.sockets.on('connection', function (socket) {
socket.emit('user-aaa5c8bbffe4db9', fullBody);
});
});
But that did not produce “instant” results, the notifications would come in to the client after a page refresh.
Client is a simple:
socket.on('user-<?php echo $_SESSION['user_display_id']; ?>', function (data) {
alert(data);
$('#events').html(data);
});
Any help would be greatly appreciated
To answer your first question. No there is no
globalin JavaScript. All the variables that are in scope where the function is defined will be available in that function.http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/