How to dynamically send a new number to the client from an express server - node.js

In the express server I have this.
app.dynamicHelpers({
dynamicValue: function(req, res) {
console.log("returning a new value");
return parseInt(Math.random() * 100);
}
});
In the client I have this.
setInterval(function() {
alert(<%= dynamicValue %>);
}
,1000);
So every second, a new number should be shown.
But that's not what happens. When the page loads a new number is generated, but the number that the client sees is always the same unless the page is reloaded.
How can this be changed to do what it's supposed to?

You are mixing server code and client code up here. The statement <%= dynamicValue %> renders the value into a script on the page:
setInterval(function() {
alert(<%= dynamicValue %>);
}
,1000);
becomes
setInterval(function() {
alert(82.9090561);
}
,1000);
This script is later interpreted by the browser. The browser has no access to the "server script code base".
In order to make this work on the client, you need to include the particular script that creates a random number on the page:
<script type="text/javascript" src="dynamic.js" />
<script type="text/javascript">
setInterval(function() {
alert(smth.dynamicValue());
}
,1000);
</script>

Related

Use the same socket.io connection in multiple HTML pages in node js

-Follwing is the jquery code I have written in my (dashboard.html) file
<script>
$(function(){
$("#username").hide();
var socket= io.connect();
$(document).on("click", ".help", function () {
alert( $(this).attr('id'));
socket.emit('help',{helper:$username.val(),requester:$(this).attr('id')});
});
});
---On clicking help button socket will emit an event "help" as you can see in the code.
---Following is the app.js file on server
io.sockets.on('connection',function(socket){
socket.on('help',function(data){
console.log('rohi is goood',data.helper);
socket.emit('loadList' , {helper:data.helper,requester:data.requester});
});
});
---On "help" event socket is emitting an event "loadList" in app.js file.
Now I want to use "loadList" event in some other html file like "chat.html".
The code I have written is as follows for chat.html.
<script>
$(function(){
// var socket= io.connect();
// var socket= io.connect('http://localhost:3000/', { 'force new //connection': true });
socket.on('loadList',function(data){
alert('inside help',$('#usernam').val());
console.log('tatai',$('#usernam').val());
if($('#usernam').val()== data.helper){
$('#chatList').append('<p>'+data.requester+'</p>'+'<button value="chat"></button>');
}
else if($('#usernam').val() == data.requester){
$('#chatList').append('<p>'+data.helper+'</p>'+'<button value="chat"></button>');
}
else {
alert('fuck off');
}
});
The above code is not working. Please tell me how can I use same socket connection in the chat.html file.(loadList event is not working).
As your question is not complete so i am assuming you want to know if socket.io connection can be used on different html pages . Yes you can access it on every html page of your application as long as you have one server on which socket.io is used .
Every time a new user comes a socket session is created for that particular user and that user can access any page of your application .

how to display a realtime variable in nodejs in HTML

I am using the setInterval() function to update a few variables(prices from various API's) every 'x' seconds in NodeJS
I want to display these variables in HTML and have them update real time every 'x' seconds.
How do I go about this using Socket.io or without using it
If you don't want to use socket.io, you can use AJAX calls but I think it's the more painful way...
If you use socket.io, there are great examples on their GitHub : Chat example.
In your NodeJS :
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', incremental);
socket.emit('update-value', incremental); // Emit on the opened socket.
incremental++;
}, 1000);
});
This code should be start in your application.
And in your view :
<html>
<body>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
My code isn't complete but shows the essential to know.
Try Templating and template engines.
Template engine are stuff that enable you to pass variables to Templates. These engines render the template file, with data you provide in form of HTML page.
I will suggest you to try 'ejs', as it very closely signify HTML files. ejs template are simply HTML syntax with placefolder for you to pass Data.
But that will require you to refresh the page continously after regular time. So you can try 'AJAX' which let you refresh part of page, simultaneously sends and receives data from server

Accessing server side functions using Express.js and EJS

I'm running a test app in Express.js using EJS as the templating engine. I'd like to access functions stored in a .js file to run server side and not client side. For instance if I have:
<%= console.log("I'm in the server console"); %>
the server catches the console output, and if I have:
<script type="text/javascript"> console.log("I'm in the client-side console"); </script>
Now if I have a function to output the same for the client side I can include it this way:
<script type="text/javascript" src="/javascripts/clientSideCode.js"> clientSideOutput(); </script>
But how do I include a file and its functions that way so EJS can execute server side code? It appears that the public folder in express is just for client side code.
You can create helper functions that your templates can access via app.locals:
http://expressjs.com/api.html#app.locals
You can use node.js and Socket.IO to emit real time events between client and server. For instance the client would do something like:
<script>window onload = function() {
socket.emit('request_customer_list', { state: "tx" });
socket.on('receive_customer_list', function(data) {
$.each(data.customer_list, function(key, value) {
socket.set(key, value); // store the customer data and then print it later
});
});}
On your server you can have a routine to load the customer list and send it back in similar format:
socket.on('connection')
socket.on('request_customer_list', function(data){
state = data.state;
var customer_list;
// pretend i loaded a list of customers from whatever source right here
socket.emit('receive_customer_list', {customer_list: customer_list});
)} )};

socket.io get data from onclick action then pass the data to other pages to execute the data

I want to create a page using node.js and socket.io.
There are two buttons inside the page, when I click one of them, it will change a variable which defines the animation-duration(I omit the CSS animation codes here).
When I open the same page on another web-browser and click one of the buttons, I hope to see the change in both of the webpages. I don't know how to write the code inside the socket.on('chat', function(data){???}); to make two pages communicate with each other.
Client side:
//socket.io codes--
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://localhost:3000');
socket.on('chat', function (data)
{
function change_position(data)
{
document.getElementById("animation1").style.WebkitAnimationDuration=data;
}
});
</script>
.....
//action--
<body>
<button id="1b" type="button" style="position:absolute; left:377px; top:220px;" value="2s"; onclick="change_position(value)"> - 1 - </button>
<button id="2b" type="button" style="position:absolute; left:477px; top:220px;" value="15s"; onclick="change_position(value)"> - 2 - </button>
</body>
server side:
var io = require('socket.io'),
connect = require('connect');
var app = connect().use(connect.static('public')).listen(3000);
var chat_room = io.listen(app);
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
chat_room.sockets.emit('chat', data);
});
});
If your want a message to propagate to all clients/sockets, in your server you should have something like:
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
socket.broadcast.emit('chat', data);
socket.emit('chat',data);
});
});
The line socket.emit('chat',data); allows you to send the message back also to the sender of it, because broadcast will send it all other sockets.
Of course, you could ommit that line and handle the message sending logic in the client; i.e. adding some JavaScript code that makes the changes you want just after sending the message to the server.
You can emit on your client using socket.emit('message', data). Then on the server get it with chat_room.socket.on('message', data). Emit it to the clients using chat_room.sockets.emit('message', data).

Consuming a Stream create using Node.JS

I have an application, which streams an MP3 using Node.JS. Currently this is done through the following post route...
app.post('/item/listen',routes.streamFile)
...
exports.streamFile = function(req, res){
console.log("The name is "+ req.param('name'))
playlistProvider.streamFile(res, req.param('name'))
}
...
PlaylistProvider.prototype.streamFile = function(res, filename){
res.contentType("audio/mpeg3");
var readstream = gfs.createReadStream(filename, {
"content_type": "audio/mpeg3",
"metadata":{
"author": "Jackie"
},
"chunk_size": 1024*4 });
console.log("!")
readstream.pipe(res);
}
Is there anyone that can help me read this on the client side? I would like to use either JPlayer or HTML5, but am open to other options.
So the real problem here was, we are "requesting a file" so this would be better as a GET request. In order to accomplish this, I used the express "RESTful" syntax '/item/listen/:name'. This then allows you to use the JPlayer the way specified in the links provided by the previous poster.
I'm assuming you didn't bother visiting their site because had you done so, you would have seen several examples of how to achieve this using HTML5/JPlayer. The following is a bare-bones example provided by their online developer's documentation:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery.jplayer.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#jquery_jplayer_1").jPlayer({
ready: function() {
$(this).jPlayer("setMedia", {
mp3: "http://www.jplayer.org/audio/mp3/Miaow-snip-Stirring-of-a-fool.mp3"
}).jPlayer("play");
var click = document.ontouchstart === undefined ? 'click' : 'touchstart';
var kickoff = function () {
$("#jquery_jplayer_1").jPlayer("play");
document.documentElement.removeEventListener(click, kickoff, true);
};
document.documentElement.addEventListener(click, kickoff, true);
},
loop: true,
swfPath: "/js"
});
});
</script>
</head>
<body>
<div id="jquery_jplayer_1"></div>
</body>
</html>

Resources