Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Stack Overflow

Wait for click before starting the game in Phaser

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

The JSFiddle demo is here, but am pasting the code below also. My question is simple (though I can’t seem to find any example in how to realize this): right now if you start the game in JSFiddle you will see that the rectangle immediately “falls” down. I would somehow like the game to start when I click with the mouse (basically that nothing happens before the first click of a mouse) – any points on how to accomplish this?

JS:

// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var game_state = {};


// Creates a new 'main' state that wil contain the game
game_state.main = function () {};
game_state.main.prototype = {

    preload: function () {
        // Change the background color of the game
        this.game.stage.backgroundColor = '#71c5cf';

        // Load the bird sprite
        this.game.load.image('bird', 'https://lh6.googleusercontent.com/Xrz0PnR6Ezg5_k5zyFKxGv0LzehAP9SMj_ga3qQzIF4JAfv8xHm7TxfliwtBD8ihfw=s190');
        this.game.load.image('pipe', 'https://lh4.googleusercontent.com/RSMNhJ3KY4Xl0PQpUf6I9EayOdLhvOKKV9QV7_BXXYVedPy0oMNRFKANW14xV76NDA=s190');
    },

    create: function () {
        // Display the bird on the screen
        this.bird = this.game.add.sprite(100, 245, 'bird');

        // Add gravity to the bird to make it fall
        this.bird.body.gravity.y = 1000;

        // Call the 'jump' function when the spacekey is hit
        var space_key = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        space_key.onDown.add(this.jump, this);

        this.pipes = game.add.group();
        this.pipes.createMultiple(20, 'pipe');
        this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);

        this.score = 0;
        var style = {
            font: "30px Arial",
            fill: "#ffffff"
        };
        this.label_score = this.game.add.text(20, 20, "0", style);

    },

    update: function () {
        // If the bird is out of the world (too high or too low), call the 'restart_game' function
        this.game.physics.overlap(this.bird, this.pipes, this.restart_game, null, this);
        if (this.bird.inWorld == false) this.restart_game();
    },


    // Make the bird jump 
    jump: function () {
        // Add a vertical velocity to the bird
        this.bird.body.velocity.y = -350;
    },

    // Restart the game
    restart_game: function () {
        // Start the 'main' state, which restarts the game
        this.game.time.events.remove(this.timer);
        this.game.state.start('main');
    },

    add_one_pipe: function (x, y) {
        // Get the first dead pipe of our group
        var pipe = this.pipes.getFirstDead();

        // Set the new position of the pipe
        pipe.reset(x, y);

        // Add velocity to the pipe to make it move left
        pipe.body.velocity.x = -200;

        // Kill the pipe when it's no longer visible 
        pipe.outOfBoundsKill = true;
    },
    add_row_of_pipes: function () {
        this.score += 1;
        this.label_score.content = this.score;
        var hole = Math.floor(Math.random() * 5) + 1;

        for (var i = 0; i < 8; i++)
        if (i != hole && i != hole + 1) this.add_one_pipe(400, i * 60 + 10);
    },
};



// Add and start the 'main' state to start the game
game.state.add('main', game_state.main);
game.state.start('main');

CSS:

#game_div {
    width: 400px;
    margin: auto;
    margin-top: 50px;
}

HTML:

<div id="game_div"></div>

I found the answer to this one myself:

So, to not leave this question unanswered and to help further readers, here is the link to the updated jsFiddle where I solved my initial problem, and below is the code from jsFiddle.

However, if one will be interested I suggest taking a look at the freely available code on GitHub which uses game states and has a better structured code.

jsFiddle

CSS:

#game_div {
    width: 400px;
    margin: auto;
    margin-top: 50px;
}

HTML:

<div id="game_div"></div>

JS:

// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var game_state = {};
var gameStarted = false;


// Creates a new 'main' state that wil contain the game
game_state.main = function () {};
game_state.main.prototype = {

    game_start: function(){
        if (!gameStarted){
            this.bird.body.gravity.y = 1000;
            this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);
            this.label_start.content = "";
        }
        gameStarted = true;
    },
    preload: function () {
        // Change the background color of the game
        this.game.stage.backgroundColor = '#71c5cf';

        // Load the bird sprite
        this.game.load.image('bird', 'https://lh6.googleusercontent.com/Xrz0PnR6Ezg5_k5zyFKxGv0LzehAP9SMj_ga3qQzIF4JAfv8xHm7TxfliwtBD8ihfw=s190');
        this.game.load.image('pipe', 'https://lh4.googleusercontent.com/RSMNhJ3KY4Xl0PQpUf6I9EayOdLhvOKKV9QV7_BXXYVedPy0oMNRFKANW14xV76NDA=s190');
    },

    create: function () {
        // Display the bird on the screen
        this.bird = this.game.add.sprite(100, 245, 'bird');

        // Add gravity to the bird to make it fall


        // Call the 'jump' function when the spacekey is hit
        this.game.input.onDown.add(this.game_start, this);

        this.pipes = game.add.group();
        this.pipes.createMultiple(20, 'pipe');


        this.score = 0;
        var style = {
            font: "30px Arial",
            fill: "#ffffff"
        };
        this.label_score = this.game.add.text(20, 20, "0", style);
        this.label_start = this.game.add.text(35, 180, "Click to start the show", style);
        game.input.onDown.add(this.jump, this);
    },

    update: function () {
        // If the bird is out of the world (too high or too low), call the 'restart_game' function
        this.game.physics.overlap(this.bird, this.pipes, this.restart_game, null, this);
        if (this.bird.inWorld == false) this.restart_game();
    },


    // Make the bird jump 
    jump: function () {
        // Add a vertical velocity to the bird
        this.bird.body.velocity.y = -350;
    },

    // Restart the game
    restart_game: function () {
        // Start the 'main' state, which restarts the game
        this.game.time.events.remove(this.timer);
        this.game.state.start('main');
        gameStarted=false;
    },

    add_one_pipe: function (x, y) {
        // Get the first dead pipe of our group
        var pipe = this.pipes.getFirstDead();

        // Set the new position of the pipe
        pipe.reset(x, y);

        // Add velocity to the pipe to make it move left
        pipe.body.velocity.x = -200;

        // Kill the pipe when it's no longer visible 
        pipe.outOfBoundsKill = true;
    },
    add_row_of_pipes: function () {
        this.score += 1;
        this.label_score.content = this.score;
        var hole = Math.floor(Math.random() * 5) + 1;

        for (var i = 0; i < 8; i++)
        if (i != hole && i != hole + 1) this.add_one_pipe(400, i * 60 + 10);
    },
};



// Add and start the 'main' state to start the game
game.state.add('main', game_state.main);
game.state.start('main');

 

Stack Overflow

How can I make sure that DELETE SQL statement in Postgres using PHP was successfull?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Is there a function which would return true of false based on if the DELETE SQL statement succeded or not? For example something like this:

<?php
    $sql = "DELETE FROM table WHERE id=123";
    $result = pg_query($sql);

    if **function**($result)
        return true;
    else
        return false;
?>

The answer, by LolCoder, was:

Use mysql_affected_rows() to get number of affected rows in mysql.

Similary for postgres, it will be pg_affected_rows.

Stack Overflow

Writing small data to file and reading from it or query the database

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I have a situation where I would have to query the database for some data which is the same for all users and changes daily, so I figured I could make a file in which I would save this data (once per day) and then load it from that file each time a user visits my site.

Now, I know that this is a common practice (caching) when the requests from database are big but the data I’m about to write to the file is a simple 3 digit number, so my question is should this still be faster or is it just an overkill and I should stick with the database query?

 The answer, by Dukeling, was:

Caching, when done right, is always faster.

It depends how long storing and retrieving data from the file takes and how long requests to the database takes.

If the database query to get the number takes long, then caching may be a good idea, since the data is small.

If you were to do a search (e.g. sequential) in a file with lots of cached data (which doesn’t seem to be the case), it would take long.

Disk I/O could be slower than database I/O (which is unlikely, unless it’s a local DB).

Bottom line – benchmark.

For your scenario, caching is probably a good idea, but if it’s only a single 3-digit number for all users then I’d just try to stick it in RAM rather than in a file.

Stack Overflow

When I click the next page in datatables my jquery selectors aren’t working anymore

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I’m using datatables plugin for jquery to show my data on the page. I have this selector when someone clicks on a row:

$('#myTable tr[class !="tableHeader"]').click(function(){
    alert("clicked!");
}

and everything is OK until I click on the “Next page” which shows me next 10 results – then this click function doesn’t show “clicked” message box anymore no matter which row I click.

I’m guessing that the problem is in a way how these new results (rows in the table) are shown, so please give me some ideas on how to solve this.

 The answer, by ghayes, was:

Use jQuery’s Live function. Live will apply to all elements on the page, even ones that don’t exist yet (I assume this is your issue). Thus, your new rows will be clickable when they are created and added to the DOM.

$('#myTable tr[class !="tableHeader"]').live('click',function(){
  alert("clicked!");
});
Stack Overflow

jQuery UI Selectable Without Selection Box

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Given this example here: http://jqueryui.com/selectable/#display-grid I would like to make a selection without the “selection box” that appears when you click ‘n drag. Namely, when I click on number 5 and drag to number 6 and then to 10 I get this:

enter image description here

where in fact what i would like to is drag from 5 to 6 to 10 and have only them selected without 9.

I searched the docs and couldn’t find that option, and my google skills didn’t bring me any luck, and I thought this must have been already done it’s just so happens I can’t grasp it on my own or find an existing solution, so any help here is appreciated (not saying you should do the research for me, am just hoping someone dealt with this before so he can point me to the right direction).

It also could be I’m missing the point in trying to accomplish this with jquery UI but this was the first such example I found that fits (kind of) what I want to accomplish.

 The rather extensive answer, by Dom, was:

First, you might want to hide .ui-selectable-helper or change the CSS:

.ui-selectable-helper{display:none;}

Next, do something like this:

$(function(){var _mousedown =false;
    $('#selectable').selectable({
        start:function(event,ui){
            _mousedown=true;},
        stop:function(event,ui){
            _mousedown=false;
            $('.ui-selected').removeClass('ui-selected');
            $('.selecting').addClass('ui-selected');},
        selecting:function(event,ui){if($('.ui-selecting').length ==1)
                $(ui.selecting).addClass('selecting');

            $('.ui-selecting').removeClass('ui-selecting');
            $('.selecting').addClass('ui-selecting');},
        unselecting:function(event,ui){if($(ui.unselecting).hasClass('selecting'))
                $(ui.unselecting).removeClass('selecting');}});

    $('#selectable').on('mouseenter','.ui-selectee',function(){if(_mousedown)
            $(this).addClass('selecting');});});

DEMO: http://jsfiddle.net/dirtyd77/7UVNS/5/ (HELPER HIDDEN)

http://jsfiddle.net/dirtyd77/7UVNS/6/ (HELPER VISIBLE)

Let me know if you have any questions!


***UPDATE:***

.selectable() is not able to do what you are looking for. However, here is something I created. Hope it helps!

JAVASCRIPT:

$(function(){var _mousedown =false,
        _last=null;    
    $('#selectable li').mousedown(function(){
        _mousedown =true;
        $('.ui-selected').removeClass('ui-selected');
        $('#selectable li').attr('unselectable','on').css('user-select','none');
        $(this).addClass('ui-selecting');}).mouseup(function(){
        _mousedown=false;  
        $('.ui-selecting').addClass('ui-selected').removeClass('ui-selecting');
        $('#selectable li').removeAttr('unselectable style');}).mouseenter(function(){if(_mousedown){if($(this).hasClass('ui-selecting'))
                $(_last).removeClass('ui-selecting');

            $(this).addClass('ui-selecting')}}).mouseleave(function(){if(_mousedown){
            _last =  $(this)[0];
            $(this).addClass('ui-selecting');}});});

DEMO: http://jsfiddle.net/dirtyd77/7UVNS/9/


***UPDATE #2:***

If you want to use this on a mobile device, I recommend changing up the format entirely to avoid any possible pitfalls. Here is how I would go about it:

JAVASCRIPT:

$(function(){var _clicked =false;
    $('#btn_select').click(function(){
        _clicked =false;
        $(this).hide();
        $('#selectable li').removeAttr('unselectable style');
        $('.ui-selecting').addClass('ui-selected').removeClass('ui-selecting');});
    $('#selectable li').click(function(){if(!_clicked){
            _clicked =true;
            $('.ui-selected').removeClass('ui-selected');
            $('#selectable li').attr('unselectable','on').css('user-select','none');
            $('#btn_select').show();}if($(this).hasClass('ui-selecting')){
            $(this).removeClass('ui-selecting');}else{
            $(this).addClass('ui-selecting');}});});

*NOTE: you might want a $('body').click() to act as the end_selection button.

DEMO: http://jsfiddle.net/dirtyd77/7UVNS/13/

Stack Overflow

How to turn off php safe mode in plesk 10?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Please tell me how to do this from the Plesk interface (version 10).

Btw, if this is not possible through Plesk 10 interface then please tell me which one of these two files I have to change:

[root@vps ~]# find /-name php.ini
/etc/php.ini
/usr/local/psa/admin/conf/php.ini

edit: Eventually I came to see that my main problem was not the safe mode but the open base dir. The link which helped me to solve that is this: remove openbasedir restriction for a specific domain in plesk which I’ll paste here in case that blog gets pulled off:

If you have an open_basedir restriction that is causing issues with a domain, you can remove the restriction easily. First, put the following text in /home/httpd/vhosts/[domain]/conf/vhost.conf:

<Directory/home/httpd/vhosts/[domain]/httpdocs>
  php_admin_flag engine on 
  php_admin_value open_basedir none
</Directory>

# If there was already a vhost.conf in the directory, then just reload Apache. Otherwise, run the magic wand:

/usr/local/psa/admin/bin/websrvmng -av

# Then bounce Apache:

/etc/init.d/httpd reload

# BUT, if the client has both php4 and php5 things get a little more complicated, and you have to add the "IfModule" directive from the apache syntax, e.g.:

< Directory /var/www/vhosts/domain.com/subdomains/SUBDOMAIN/httpdocs>
< IfModule sapi_apache2.c>
      php_admin_flag engine on
      php_admin_flag safe_mode off
      php_admin_value open_basedir none
< /IfModule>
< IfModule mod_php5.c>
      php_admin_flag engine on
      php_admin_flag safe_mode off
      php_admin_value open_basedir none
< /IfModule>
      Options +Includes -ExecCGI
< /Directory>

# Or if you want to add a new location to open_basedir instead of disabling open_basedir, you would have:

php_admin_value open_basedir "/var/www/vhosts/domain.com/httpdocs:/tmp:/new/path/comes/here"

 

The answer, by Eric G, was:

Go to the control panel for the specific domain where you want to turn off safe mode, click on the Websites & Domains tab. At the bottom will be a listing of the domain names, click on an individual name to see it’s hosting settings. There should be a checkbox for PHP, and another one for whether or not to use safe mode.

See also: https://manage.grabweb.in/knowledgebase.php?action=displayarticle&id=86

Stack Overflow

Should I use Node.js only or behind Apache or Nginx

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

I wondered about basically the same quesiton as user 7cows had: In what cases should one prefer to use Node.js only as a server in real deployment? When one does not want to use Node.js only, what plays better with Node.js, Apache or Nginx?

The answer, by pauljz, was:

There are several good reasons to stick another webserver in front of Node.js:

  • Not having to worry about privileges/setuid for the Node.js process. Only root can bind to port 80 typically. If you let nginx/Apache worry about starting as root, binding to port 80, and then relinquishing its root privileges, it means your Node app doesn’t have to worry about it.
  • Serving static files like images, css, js, and html. Node may be less efficient compared to using a proper static file web server (Node may also be faster in select scenarios, but this is unlikely to be the norm). On top of files serving more efficiently, you won’t have to worry about handling eTags or cache control headers the way you would if you were servings things out of Node. Some frameworks may handle this for you, but you would want to be sure. Regardless, still probably slower.
  • As Matt Sergeant mentioned in his answer, you can more easily display meaningful error pages or fall back onto a static site if your node service crashes. Otherwise users may just get a timed out connection.
  • Running another web server in front of Node may help to mitigate security flaws and DoS attacks against Node. For a real-world example, CVE-2013-4450 is prevented by running something like Nginx in front of Node.

I’ll caveat the second bullet point by saying you should probably be serving your static files via a CDN, or from behind a caching server like Varnish. If you’re doing this it doesn’t really matter if the origin is Node or Nginx or Apache.

Caveat with nginx specifically: if you’re using websockets, make sure to use a recent version of nginx (>= 1.3.13), since it only just added support for upgrading a connection to use websockets.

Also, user Matt Sergeant added:

Just to add one more reason to pauljz’s answer, I use a front end server so that it can serve up 502 error pages when I’m restarting the backend server or it crashes for some reason. This allows your users to never get an error about unable to establish a connection.

Stack Overflow

Get/Set values of dynamical generated input fields using ng-repeat in Angular

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I have an input field which once filled with a number populates that count of additional input fields. I can’t figure out how to get the values inserted in those generated input fields. Any help is appreciated, and oh, I did try various things and even with angular.element, or solely with jquery, but failed, so any explanation on how to do this is welcome.

Here is my jsfiddle, and the code c/p-ed here:

<div ng-controller="MyCtrl">
    <input type="text" ng-model="cntInputs" placeholder="#Inputs"><br/>

    <input ng-repeat="i in getTimes()" type="text" placeholder="{{i}}" id="input_{{i}}">

    <ul>
        <li ng-repeat="j in getTimes()">
            Inputed value is: {{getValue(j)}}
        </li>
    </ul>
</div>

js:

var myApp = angular.module('myApp', []);


function MyCtrl($scope) {
    $scope.cntInputs = 0;

    $scope.getTimes=function(){
        var a = new Array();

        for(var i=1; i <= $scope.cntInputs; i++)
            a.push(i);

        return a;       
    };

    $scope.getValue = function(id){
        //here get the value of that inserted in the element with the id of "input_" + id
        return angular.element("input_" + id);
    }
}

The answer, by James Kleeh, was:

So add ng-model="inputs[i-1]" to your text field

Then in your controller add $scope.inputs= [];

Then in your getValue function: return $scope.inputs[id-1];

If you make your getTimes function 0 based you wouldn’t need the -1s

Updated your fiddle: http://jsfiddle.net/7MhLd/60/

Stack Overflow

Webkitdotnet unable to load https site

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I am using this webkitdotnet in my C# project. It all went well until I had to use access site with https.

I’ve searched their forum and found few posts about this but none of it solves my problem, so please shed some light on this one. Thx!

edit: Also as mentioned in their threads (also without an answer) I get a “Peer certificate cannot be authenticated with known CA certificates” error when trying to access my server, buthttps://www.google.com works fine.

They also mention the “apple” build which worked fine with ssl (at least so they say), but I can’t find it anywhere…

The answer, by therealmitchconnors, was:

This is a bit of a hack, but you can make webkitdotnet ingore peer ssl errors. WebKitDotNet uses WebKit, which, in turn uses curl, which is responsible for your wonderful ssl error there. curl exposes an option to ignore ssl errors, but neither webkit nor webkitdotnet seem to expose this functionality in their api. However, if you checkout the webkit source code, webkit sets the curl option (CURLOPT_SSL_VERIFYPEER) to false if the value of the environment variable WEBKIT_IGNORE_SSL_ERRORS is set to true.

What this all boils down to is that if you set the environment variable in code before initializing either webkit or webkitdotnet components, webkit will ignore the bad certificate and allow you to navigate to the site (sort of like clicking Proceed Anyway on IE9’s Bad Certificate Warning page).

C++:

setvar("WEBKIT_IGNORE_SSL_ERRORS", "1");

C#:

Environment.SetEnvironmentVariable("WEBKIT_IGNORE_SSL_ERRORS", "1");

If anyone is interested, the webkit source code referenced is in file webkit\Source\WebCore\platform\network\curl\ResourceHandleManager.cpp at lines 65 and 681, currently.

Stack Overflow

NodeJS code executes differently when run via browser and when run via curl in terminal

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I have the following simple NodeJS code:

var http = require("http");

http.createServer(function(request, response){
    response.writeHead(200);
    setTimeout(function(){
        response.write("This printed 3 secs later, ait?");
        response.end();},3000);

    response.write("This will be printed before.\n");}).listen(8080);

If I run the script with node scriptname.js and then access it via curl in terminal like this:

curl http://localhost:8080

I get an output as expected, first it prints This will be printed before., then after 3 seconds it prints This printed 3 secs later, ait?.

However, when I open http://localhost:8080 in my browser (newest versions of Chrome, Firefox) page loads for 3 seconds and it prints the text This will be printed before. This printed 3 secs later, ait? all at once. Why does this happen and how could I make the same behavior in the browser?

edit: So, as Ken stated in his answer

…this is simply due to the behavior of the browser rendering engine to render the contents. The rendering engine cashes the contents until response.end();

and advised to go and check out Socket.IO, I came up with this working example which uses expressand Socket.IO:

//timeoutTest.js
var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(8080);

app.use(express.static(__dirname +'/'));

app.get('/',function(req, res){
   res.sendfile(__dirname +'/timeoutTest.html');});

io.sockets.on('connection',function(client){
   client.emit('msg',"This prints right now on connection.");

   setTimeout(function(){
      client.emit('msg',"This prints out after 3 secs.");},3000);});
//timeoutTest.html
<!DOCTYPE html><html><head><script src="/socket.io/socket.io.js"></script><script src="jquery.js"></script><script>
    $(document).ready(function(){var server = io.connect('http://localhost');
        server.on('msg',function(data){
            $('body').append(data +"<br/>");});});</script></head><body></body></html>

 

The answer, by Ken OKABE, was:

I think this is simply due to the behavior of the browser rendering engine to render the contents. The rendering engine cashes the contents until response.end(); arrives, then renders whole.

Basically, HTML contents in the browser are never updated automatically by incremental server pushsuch as response.write. You must pull data from the server to the browser client by Ajax and DHTML/js technique. curl in terminal is completely different story in terms of the mere output of the node server.

If you seek more interactive behavior between node server and browser client, if you want server push feature, websocket is the way to go, and also investigate node stream stuff. Socket.IO is famous, and for node stream https://github.com/substack/stream-handbook should be interesting to you.

I personally do this on my own project: http://kenokabe.github.io/MarkdownLive/. I write stuff using Markdown and needed a streaming preview, so I created by myself. The preview screen is a Browser HTML page, and the HTML contents rendered and updated incrementally in streaming manner.

Page 6 of 9« First...«5678»...Last »

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak