Follow the instruction:
sudo apt-get install npm
npm install -g npm
npm install socket.io
sudo npm install -g n
- sudo apt-get install node
- sudo npm install xml2json
Now create file in same folder:
server.js
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
parser = new require('xml2json'),
fs = require('fs');
// creating the server ( localhost:8000 )
app.listen(8000);
console.log('server listening on localhost:8000');
// on server started we can load our client.html page
function handler(req, res) {
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
}
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
console.log(__dirname);
// watching the xml file
fs.watchFile(__dirname + '/example.xml', function(curr, prev) {
// on file change we can read the new xml
fs.readFile(__dirname + '/example.xml', function(err, data) {
if (err) throw err;
// parsing the new xml data and converting them into json file
var json = parser.toJson(data);
// send the new data to the client
socket.volatile.emit('notification', json);
});
});
});
example.xml
<?xml version="1.0" encoding="ISO-8859-1"?><test>
<sample>Hello world!</sample>
</test>
client.html
<html><head>
<title>Push notification server</title>
</head>
<body>
<time></time>
<div id="container">Try to change your xml data to update this content</div>
<script src="socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
// creating a new websocket
var socket = io.connect('http://10.10.50.136:8000');
// on every message recived we print the new datas inside the #container div
socket.on('notification', function (data) {
// convert the json string into a valid javascript object
var _data = JSON.parse(data);
$('#container').html(_data.test.sample);
$('time').html('Last Update:' + new Date());
});
</script>
</body>
</html>
Please tell me if you get any error...