<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>nodejs &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/nodejs/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Diving into Node.js &#8211; A Long Polling Example</title>
		<link>/2010/12/02/diving-into-node-js-a-long-polling-example/</link>
		<comments>/2010/12/02/diving-into-node-js-a-long-polling-example/#comments</comments>
		<pubDate>Thu, 02 Dec 2010 09:51:48 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[chat-like applications]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[Hypertext Transfer Protocol]]></category>
		<category><![CDATA[Internet protocols]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[long polling server]]></category>
		<category><![CDATA[Node]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[real time data]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[typical web server]]></category>
		<category><![CDATA[web developers]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[web servers]]></category>
		<category><![CDATA[World Wide Web]]></category>
		<category><![CDATA[XMLHttpRequest]]></category>

		<guid isPermaLink="false">/?p=2041</guid>
		<description><![CDATA[Node.js vs. The World What is typical for most of the web servers is that they listen for requests and respond as quickly as possible on every one of them. In fact the speed of the response is one of the main targets of optimization for developers. Fast servers are what everyone needs. From web &#8230; <a href="/2010/12/02/diving-into-node-js-a-long-polling-example/" class="more-link">Continue reading <span class="screen-reader-text">Diving into Node.js &#8211; A Long Polling Example</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/11/19/diving-into-node-js-very-first-app/" rel="bookmark" title="Diving into Node.js &#8211; Very First App">Diving into Node.js &#8211; Very First App </a></li>
<li><a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="bookmark" title="Diving into Node.js &#8211; Introduction &#038; Installation">Diving into Node.js &#8211; Introduction &#038; Installation </a></li>
<li><a href="/2010/03/23/read-remote-file-content-type-with-zend_http_client/" rel="bookmark" title="Read Remote File Content-Type with Zend_Http_Client">Read Remote File Content-Type with Zend_Http_Client </a></li>
<li><a href="/2011/04/13/post-with-zend_http_client/" rel="bookmark" title="POST with Zend_Http_Client">POST with Zend_Http_Client </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Node.js vs. The World</h2>
<p><a href="/wp-content/uploads/2010/11/node-js.jpg"><img class="aligncenter size-full wp-image-2088" title="node js" src="/wp-content/uploads/2010/11/node-js.jpg" alt="" width="445" height="193" srcset="/wp-content/uploads/2010/11/node-js.jpg 445w, /wp-content/uploads/2010/11/node-js-300x130.jpg 300w" sizes="(max-width: 445px) 100vw, 445px" /></a></p>
<p>What is typical for most of the web servers is that they listen for requests and respond as quickly as possible on every one of them. In fact the speed of the response is one of the main targets of optimization for developers. Fast servers are what everyone needs. From web developers to website visitors!</p>
<p>In the field of the that battle different web servers have different &#8220;weapons&#8221; to gain time. While this is useful in most of the cases, when it comes to a chat-like applications and <a title="Node.js" href="http://nodejs.org/" target="_blank">Node.js</a> approaches, the response is not always immediately returned. As I described in my <a title="Diving into Node.js – Very First App" href="/2010/11/19/diving-into-node-js-very-first-app/" target="_self">posts</a> until now about Node.js, a simple web server may wait for an event to be emitted, and than return the response.<span id="more-2041"></span></p>
<p>I wrote about <a title="Diving into Node.js – Very First App" href="/2010/11/19/diving-into-node-js-very-first-app/" target="_self">how to write the very first server</a>, but than I didn&#8217;t described how to make a &#8220;non-responding&#8221; server. By the term &#8220;non-responding&#8221; I mean a server that responds not immediately after it has received and parsed/executed the request.</p>
<p>A typical web server, responding immediately on every request, written with Node, this may look like so:</p>
<pre lang="javascript">var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</pre>
<p>The code that shows us that the request is executed and responds in these lines:</p>
<pre lang="javascript">  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
</pre>
<p>Actually by commenting/removing those lines you&#8217;ll get a server that simply doesn&#8217;t respond &#8211; ever! This of course is not the main goal, but you can start from somewhere.</p>
<pre lang="javascript">var http = require('http');
http.createServer(function (req, res) {
  // res.writeHead(200, {'Content-Type': 'text/plain'});
  // res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</pre>
<p>This is how you can hold for a while. Perhaps putting these lines in a conditional statement and periodically checking for some event to occur will do the job.</p>
<pre lang="javascript">var http = require('http');
http.createServer(function (req, res) {
  if (something) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World\n');
  }
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</pre>
<h2>Looping Server</h2>
<p>As described in the code above if you put the respond into a conditional you can possibly return the response after some event has fired. The only thing is to periodically loop and check for this condition to be true. Assuming your server&#8217;s code is in server.js, started with the &#8220;node server.js&#8221; command, you&#8217;ve to put this code into it:</p>
<pre lang="javascript" escaped="true">var http = require("http"),
    fs	 = require("fs");  

// we create a server with automatically binding
// to a server request listener
http.createServer(function(request, response) {
	checkFile(request, response);
}).listen(8124);

function checkFile(request, response)
{
	var date = new Date();
	if (date-request.socket._idleStart.getTime() &gt; 59999) {
		response.writeHead(200, {
			'Content-Type'   : 'text/plain',
			'Access-Control-Allow-Origin' : '*'
		});

		// return response
		response.write('OK', 'utf8');
		response.end();
	}

	// we check the information from the file, especially
	// to know when it was changed for the last time
	fs.stat('filepath', function(err, stats) {
		// if the file is changed
		if (stats.mtime.getTime() &gt; request.socket._idleStart.getTime()) {
			// read it
			fs.readFile('filepath', 'utf8', function(err, data) {
				// return the contents
				response.writeHead(200, {
					'Content-Type'   : 'text/plain',
					'Access-Control-Allow-Origin' : '*'
				});

				// return response
				response.write(data, 'utf8');
				response.end();

				// return
				return false;
			});
		}
	});	

	setTimeout(function() { checkFile(request, response) }, 10000);
};
</pre>
<p>Note: you must change &#8220;filepath&#8221; with an existing file path in your system.</p>
<p>Here we can read periodically the file&#8217;s mtime, which is the modify time. Thus whenever the file is changed the server will return the response. It&#8217;s interesting to note that if no change occurs within the timeout period you&#8217;ve to return some status message as we did in those lines:</p>
<pre lang="javascript" escaped="true">        
var date = new Date();
if (date-request.socket._idleStart.getTime() > 59999) {
	response.writeHead(200, {
		'Content-Type'   : 'text/plain',
		'Access-Control-Allow-Origin' : '*'
	});
	
	// return response
	response.write('OK', 'utf8');
	response.end();
}
</pre>
<p>The client side should long poll this server. The example bellow is written in jQuery. The only &#8220;special&#8221; thing is that after receiving the response, you must call the server again.</p>
<h3>The Client</h3>
<p>The client is nothing new to the jQuery/JavaScript community except you must call again the server when the response is returned:</p>
<pre lang="javascript">function callNode() {
    $.ajax({
        cache : false,
		// setup the server address
        url : 'http://www.example.com:8124/',
        data : {},
        success : function(response, code, xhr) {

            if ('OK' == response) {
            	callNode();
                return false;
            }

            // do whatever you want with the response
            ...

            // make new call
            callNode();
        }
    });
};
callNode();
</pre>
<h2>Summary</h2>
<p>As Node can hold the response, the only thing you should do is to check periodically for something as in this example this was a file change. Than it&#8217;s important to change the client so it can call the server after the response from it is received.</p>
<p>Typically Node can be used for chat-like applications or whatever apps that must deliver real time data, but for sure it is really great software.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/11/19/diving-into-node-js-very-first-app/" rel="bookmark" title="Diving into Node.js &#8211; Very First App">Diving into Node.js &#8211; Very First App </a></li>
<li><a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="bookmark" title="Diving into Node.js &#8211; Introduction &#038; Installation">Diving into Node.js &#8211; Introduction &#038; Installation </a></li>
<li><a href="/2010/03/23/read-remote-file-content-type-with-zend_http_client/" rel="bookmark" title="Read Remote File Content-Type with Zend_Http_Client">Read Remote File Content-Type with Zend_Http_Client </a></li>
<li><a href="/2011/04/13/post-with-zend_http_client/" rel="bookmark" title="POST with Zend_Http_Client">POST with Zend_Http_Client </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/12/02/diving-into-node-js-a-long-polling-example/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
	</channel>
</rss>
