<?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>Mixu&#039;s tech blog &#187; Technology</title>
	<atom:link href="http://blog.mixu.net/category/tech/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.mixu.net</link>
	<description>When I read what I write I learn what I think</description>
	<lastBuildDate>Tue, 31 Jan 2012 23:14:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Performance benchmarking Socket.io 0.8.7, 0.7.11 and 0.6.17 and Node&#8217;s native TCP</title>
		<link>http://blog.mixu.net/2011/11/22/performance-benchmarking-socket-io-0-8-7-0-7-11-and-0-6-17-and-nodes-native-tcp/</link>
		<comments>http://blog.mixu.net/2011/11/22/performance-benchmarking-socket-io-0-8-7-0-7-11-and-0-6-17-and-nodes-native-tcp/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 23:07:37 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=2088</guid>
		<description><![CDATA[I&#8217;ve been working with Socket.io quite a bit recently. It&#8217;s a great library. However, after upgrading to 0.8.x, I ran into problems with increased CPU usage. Since performance is very important for high traffic pubsub implementations, I decided to investigate this further &#8211; and try to quantify the performance impact of upgrading to a newer [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working with Socket.io quite a bit recently. It&#8217;s a great library. However, after upgrading to 0.8.x, I ran into problems with increased CPU usage. Since performance is very important for high traffic pubsub implementations, I decided to investigate this further &#8211; and try to quantify the performance impact of upgrading to a newer version of Socket.io.</p>
<p>I wrote a benchmarking suite (<a href="https://github.com/mixu/siobench">siobench</a>). The benchmark is rather simple. Clients connect one at a time, and a new client is only allowed to connect when the previous one is connected. When the server has used up 5000 milliseconds of CPU time, the benchmark is stopped. Every second, every connected client sends a single message which is echoed back by the server (<a href="https://github.com/mixu/siobench">more details</a>).</p>
<p>This workload is geared towards a situation where Socket.io is used to notify people of things as part of a larger application: e.g. most of the load is assumed to be idling connections rather than real-time messaging like in, say, a multiplayer game.</p>
<p>The &#8220;end of test&#8221; condition is 5000 ms of CPU time, because this seemed to be a easy way to give all implementations the same amount of time. CPU usage % is not accurate, since it is dependent on how much CPU time the process gets over a particular amount of wallclock time. In the graphs the CPU usage % calculated over a 100ms interval, while usertime and systime are the actual numbers reported at that particular time.</p>
<h2>Summary</h2>
<table>
<tbody>
<tr>
<td>Node (0.4.12) using tcp</td>
<td>~ 8000 connections on a single core</td>
</tr>
<tr>
<td>socket.io 0.6.17 using websockets</td>
<td>~ 2300 connections on a single core</td>
</tr>
<tr>
<td>socket.io 0.7.11 using websockets</td>
<td>~ 1800 connections on a single core</td>
</tr>
<tr>
<td>socket.io 0.8.6 using websockets</td>
<td>~ 1900 connections on a single core</td>
</tr>
</tbody>
</table>
<p>Remember, this is just one server on one core, with 5000 ms of CPU time on that core. The rest of the cores are used to generate sufficient load. The full graphs are at the end of the post.</p>
<p>Note that the absolute numbers are mostly unimportant &#8211; I ran this on the following 15&#8243; Macbook Pro running Arch with the 3.1.04 Linux kernel in Virtualbox with 4096 Mb of RAM, a SSD and four cores (Intel(R) Core(TM) i7-2635QM CPU @ 2.00GHz GenuineIntel GNU/Linux). You can get numbers that are more representative of your system <a href="https://github.com/mixu/siobench">by getting siobench</a> and running it:</p>
<pre>Usage: node siobench.js [env]
A tool for benchmarking your Socket.io server.

Available environments:
	0.6.17
	0.6.17_poll
	0.7.11
	0.8.7
	0.8.7_poll
	tcp</pre>
<div>
<p>You can also write your own benchmarks under ./bench, by writing a new server.js (<a href="https://github.com/mixu/siobench/blob/master/bench/tcp/server_tcp.js">example #1</a>, <a href="https://github.com/mixu/siobench/blob/master/bench/sio087/server.js">#2</a>) and a new client.js (<a href="https://github.com/mixu/siobench/blob/master/bench/tcp/client_tcp.js">example #1</a>, <a href="https://github.com/mixu/siobench/blob/master/bench/sio087/client.js">#2</a>). Each benchmark has it&#8217;s own set of npm dependencies installed, so that one can run benchmarks against many versions of socket.io.</p>
<p><strong>Some notes on performance</strong></p>
<p>The relative performance is more interesting.</p>
<p>First, the node TCP speed represents the highest achievable performance on this benchmark, since it only uses the built-in TCP implementation. Compared to this, Socket.io is has about 1/3 of the performance (~ 2300 vs ~8000 connections) when using WebSockets.</p>
<p>Second, it appears that 0.8.7 is about 20% slower than 0.6.17 on this benchmark. If I remember correctly, Socket.io 0.7 switched to a new protocol, and there are clearly some performance improvements over 0.7.11 in 0.8.7 (+100 connections in this bench); it&#8217;s just that the overall performance is still worse in this benchmark than in the old 0.6.17 branch.</p>
<div>
<p><strong>Working towards higher-performance</strong></p>
</div>
<p>As this is just a simple benchmark, I don&#8217;t really have solutions &#8211; only some suggestions.</p>
<p><strong>1) A CI build that includes benchmarks and community contributed test cases</strong></p>
<p>First, I&#8217;d love to see a CI build for Socket.io that would include performance benchmarks and community contributed test cases.</p>
<p>However, currently setting up a CI build for Socket.io is difficult because <a href="https://github.com/LearnBoost/socket.io/issues/519">the bundled test suite only works on OSX</a>. It would be a lot easier to contribute if the tests worked on other platforms.</p>
<p>I am hoping that as <a href="https://github.com/LearnBoost/engine.io">Engine.io gets going</a>, the test suite will be fixed so that it can be run on other platforms. Otherwise, contributing improvements will be tricky/impossible since there is no way to tell whether the code works.</p>
<p><strong>2) More realistic performance test scenarios</strong></p>
<p>The current test scenario is rather limited in that it mostly tests performance in terms of establishing connections (without terminating them). I&#8217;d love to hear more realistic scenario suggestions, particularly from people who have run into memory usage issues.</p>
<p><a href="https://github.com/mixu/siobench">siobench</a> is only a starting point: it&#8217;s way better than just looking at htop and wondering whether performance was better in the last version or not. There are still specific questions that should be formulated as replicable tests.</p>
<p><strong>3) A polling transport that works on Node.js</strong></p>
<p>I did write tests for the xhr-polling transport for Socket.io as well. These showed much worse performance, around:</p>
<ul>
<li>~ 550 connections on Socket.io 0.6.17 (vs ~2300 using WS)</li>
<li>~ 450 connections on Socket.io 0.8.7 (vs ~ 1900 using WS)</li>
</ul>
<p>However, the xhr-polling is severely broken in that it stops connecting after 4-5 connections on Node v0.4.12. So I had to force each load generating client to only make four connections and then spawn a new load generating process to work around the problem. I wouldn&#8217;t vouch for the accuracy of the test with xhr-polling until the xhr-polling transport is fixed on Node when using socket.io-client (it&#8217;s been broken for the last three releases, though).</p>
<p><strong>4) Comparative benchmarks</strong></p>
<p>Hopefully, this will help with performance testing new releases of Socket.io and other Comet libraries. Since the plan is that Engine.io will allow people to work with a lower level than Socket.io, there might be new performance oriented versions, and it would be useful to see benchmarks for those. Re: the other Node.js pubsub frameworks: I can&#8217;t benchmark Faye, because it does not provide the right API out of the box, and Juggernaut uses Socket.io internally.</p>
<p>I&#8217;m going to use siobench it for internal testing to ensure that the pubsub implementation I am working on (built over Socket.io) will not have performance regressions.</p>
<p>The full graphs are below. Please leave comments and suggestions for improvements &#8211; I am hoping that the developer community around Socket.io can help in improving the performance going forward, kind of like what Mozilla did with &#8220;<a href="http://arewefastyet.com/">arewefastyet.com</a>&#8220;.</p>
</div>
<p><strong>Socket.io 0.6.17 &#8211; Websockets &#8211; CPU usage and time</strong></p>
<p><a href="http://blog.mixu.net/files/2011/11/sio_617_cpu.png"><img class="alignnone size-full wp-image-2115" title="sio_617_cpu" src="http://blog.mixu.net/files/2011/11/sio_617_cpu.png" alt="" width="384" height="288" /></a> <a href="http://blog.mixu.net/files/2011/11/sio_617_cputime.png"><img class="alignnone size-full wp-image-2116" title="sio_617_cputime" src="http://blog.mixu.net/files/2011/11/sio_617_cputime.png" alt="" width="384" height="288" /></a></p>
<p><strong>Socket.io 0.6.17 &#8211; Websockets &#8211; resident set size</strong></p>
<div><strong><a href="http://blog.mixu.net/files/2011/11/sio_617_mem.png"><img title="sio_617_mem" src="http://blog.mixu.net/files/2011/11/sio_617_mem.png" alt="" width="384" height="288" /></a><br />
</strong></div>
<p>&nbsp;</p>
<p><strong>Socket.io 0.7.11 &#8211; Websockets &#8211; CPU usage and time</strong></p>
<p><a href="http://blog.mixu.net/files/2011/11/sio_711_cpu.png"><img class="alignnone size-full wp-image-2119" title="sio_711_cpu" src="http://blog.mixu.net/files/2011/11/sio_711_cpu.png" alt="" width="384" height="288" /></a><a href="http://blog.mixu.net/files/2011/11/sio_711_cputime.png"><img class="alignnone size-full wp-image-2120" title="sio_711_cputime" src="http://blog.mixu.net/files/2011/11/sio_711_cputime.png" alt="" width="384" height="288" /></a></p>
<p><strong>Socket.io 0.7.11 &#8211; Websockets &#8211; resident set size</strong></p>
<p><a href="http://blog.mixu.net/files/2011/11/sio_711_mem.png"><img class="alignnone size-full wp-image-2120" title="sio_711_cputime" src="http://blog.mixu.net/files/2011/11/sio_711_mem.png" alt="" width="384" height="288" /></a></p>
<p><strong>Socket.io 0.8.7 &#8211; Websockets &#8211; CPU usage and time</strong></p>
<p><a href="http://blog.mixu.net/files/2011/11/sio_87_cpu.png"><img class="alignnone size-full wp-image-2120" title="sio_87_cpu" src="http://blog.mixu.net/files/2011/11/sio_87_cpu.png" alt="" width="384" height="288" /></a><a href="http://blog.mixu.net/files/2011/11/sio_87_cputime.png"><img class="alignnone size-full wp-image-2120" title="sio_87_cputime" src="http://blog.mixu.net/files/2011/11/sio_87_cputime.png" alt="" width="384" height="288" /></a></p>
<p><strong>Socket.io 0.8.7 &#8211; Websockets &#8211; resident set size</strong></p>
<p><a href="http://blog.mixu.net/files/2011/11/sio_87_mem.png"><img class="alignnone size-full wp-image-2120" title="sio_87_mem" src="http://blog.mixu.net/files/2011/11/sio_87_mem.png" alt="" width="384" height="288" /></a></p>
<p><strong>Node 0.4.12 &#8211; TCP &#8211; CPU usage and time</strong></p>
<p><a href="http://blog.mixu.net/files/2011/11/tcp_cpu.png"><img class="alignnone size-full wp-image-2120" title="tcp_cpu" src="http://blog.mixu.net/files/2011/11/tcp_cpu.png" alt="" width="384" height="288" /></a><a href="http://blog.mixu.net/files/2011/11/tcp_cputime.png"><img class="alignnone size-full wp-image-2120" title="tcp_cputime" src="http://blog.mixu.net/files/2011/11/tcp_cputime.png" alt="" width="384" height="288" /></a></p>
<p><strong>Node 0.4.12 &#8211; TCP &#8211; resident set size</strong></p>
<p><a href="http://blog.mixu.net/files/2011/11/tcp_mem.png"><img class="alignnone size-full wp-image-2120" title="tcp_mem" src="http://blog.mixu.net/files/2011/11/tcp_mem.png" alt="" width="384" height="288" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/11/22/performance-benchmarking-socket-io-0-8-7-0-7-11-and-0-6-17-and-nodes-native-tcp/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>My Arch Linux setup</title>
		<link>http://blog.mixu.net/2011/11/10/my-arch-linux-setup/</link>
		<comments>http://blog.mixu.net/2011/11/10/my-arch-linux-setup/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 04:22:41 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[How-to]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=2033</guid>
		<description><![CDATA[This is mostly just a reminder for myself &#8211; but I always learn new things when I read how other people set up their system. Leave a comment if you have a tip &#8211; that&#8217;s how I learned about wicd-gtk . Oh, and install my window manager (tiling, written in C++ and node.js, configurable using Javascript). [...]]]></description>
			<content:encoded><![CDATA[<p>This is mostly just a reminder for myself &#8211; but I always learn new things when I read how other people set up their system. Leave a comment if you have a tip &#8211; that&#8217;s how I learned about wicd-gtk <img src='http://blog.mixu.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Oh, and install <a href="https://github.com/mixu/nwm">my window manager</a> (tiling, written in C++ and node.js, configurable using Javascript).</p>
<p><strong>First steps</strong></p>
<ul>
<li>do the basic arch setup first (or <a href="https://wiki.archlinux.org/index.php/Installing_Arch_Linux_in_VMware">VMware</a>, or Virtualbox)</li>
</ul>
<p><strong>Update the system (and install/setup sudo)</strong></p>
<pre>dhcpcd eth0 #if you did not add "interface=eth0" in rc.conf during setup
pacman -Syu</pre>
<p>Fixes:</p>
<p><a href="http://www.archlinux.org/news/initscripts-update-manual-intervention-required/">http://www.archlinux.org/news/initscripts-update-manual-intervention-required/</a></p>
<pre>rm /etc/profile.d/locale.sh</pre>
<p><a href="http://www.archlinux.org/news/filesystem-upgrade-manual-intervention-required/">http://www.archlinux.org/news/filesystem-upgrade-manual-intervention-required/</a></p>
<pre>pacman -S filesystem --force</pre>
<pre>pacman -S sudo
vim /etc/sudoers # add yourself to sudoers
sudo vim /etc/pacman.conf # set SigLevel = Never TrustAll
sudo shutdown-r now</pre>
<p>Install X11:</p>
<pre>pacman -S xorg-server xorg-xinit xorg-utils xorg-server-utils xterm</pre>
<p>If virtualized in VirtualBox, make copy-paste work first:</p>
<pre>pacman -S virtualbox-archlinux-additions</pre>
<p><a href="https://wiki.archlinux.org/index.php/Arch_Linux_VirtualBox_Guest#Arch_Linux_guests">Details</a></p>
<p><strong> Create a new user</strong></p>
<pre>pacman -S zsh
useradd -m -g users -G audio,lp,optical,storage,video,games,power,scanner -s /bin/zsh USERNAME
su USERNAME
passwd</pre>
<p><strong>Add x11</strong></p>
<pre>pacman -S xorg-server xorg-xinit xorg-utils xorg-server-utils</pre>
<p><strong>Copy ssh keys over from old machine</strong><br />
<strong>Useful packages</strong></p>
<pre>pacman -S base-devel sudo python2 git libev mlocate mercurial nitrogen \
sakura wicd-gtk pcmanfm gnome-icon-theme htop unzip \
openssl chromium flashplugin bash-completion xterm \
epdfview mysql ruby tilda tmux wget redis xcursor-vanilla-dmz \
xarchiver gzip bzip2 zip unzip unrar p7zip \
meld ttf-ubuntu-font-family mpg123 alsa-utils redis mysql ruby libxslt</pre>
<ul>
<li>base-devel and python2 for compiling node</li>
<li>libev for nwm</li>
<li>mlocate for locate command</li>
<li>nitrogen is better than feh for multiple screens</li>
<li>sakura is a nice terminal</li>
<li>wicd-gtk is a simple wifi network gui</li>
<li>pcmanfm gnome-icon-theme are for pcmanfm, a Nautilus alternative</li>
</ul>
<p>Remember to visudo and remove the password requirement from wheel. And add dbus and wicd to /etc/rc.conf just like pacman tells you to.<br />
<strong>Configuring X11</strong></p>
<p>Add ~/.Xresources:</p>
<pre>Xcursor.theme: vanilla-dmz
Xcursor.size:  16       !  32, 48 or 64 may also be good values</pre>
<p><strong>Configuring git</strong></p>
<pre>git config --global color.ui true</pre>
<p><strong>Configuring sakura</strong></p>
<p>I want to use ctrl + Page_Up / Page_Down to switch tabs, so edit ~/.config/sakura/sakura.conf:</p>
<pre>switch_tab_accelerator=4 # since <a>GDK_CONTROL_MASK</a> is 1 &lt;&lt; 2, e.g. 4.
prev_tab_key=Page_Down
next_tab_key=Page_Up</pre>
<p><strong>Some basic niceties: whatprovides, service and chkconfig</strong></p>
<pre>pacman -S pkgtools</pre>
<ul>
<li>pkgtools provides the pkgfile tool. It works like yum whatprovides (e.g. allows you to search for a particular command or dependency in all the pacman packages)</li>
<li>&#8220;sudo pkgfile -u&#8221; to update the db</li>
<li>&#8220;pgkfile zipinfo&#8221; to search for zipinfo</li>
</ul>
<p>Arch don&#8217;t have a service and chkconfig, but we can make the new things curve a bit less steep by adding some functions to .bashrc:</p>
<pre>function service() {
  sudo /etc/rc.d/$1 $2
}

alias chkconfig='cat /etc/rc.conf | grep DAEMONS &amp;&amp; echo "cat + grep /etc/rc.conf"'</pre>
<p>This makes service an alias for /etc/rc.d/ and prints out the enabled services from /etc/rc.conf. While we&#8217;re editing .bashrc, might as well add:</p>
<pre>PS1="[\W]\$ " # my preferred bash prompt (e.g. only the current dirname).
ulimit -s 16400 # higher stack limit
# ssh-agent
SSH_ENV="$HOME/.ssh/environment"
function start_agent {
     echo "Initialising new SSH agent..."
     /usr/bin/ssh-agent | sed 's/^echo/#echo/' &gt; "${SSH_ENV}"
     echo succeeded
     chmod 600 "${SSH_ENV}"
     . "${SSH_ENV}" &gt; /dev/null
     /usr/bin/ssh-add;
}
# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
     . "${SSH_ENV}" &gt; /dev/null
     #ps ${SSH_AGENT_PID} doesn't work under cywgin
     ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ &gt; /dev/null || {
         start_agent;
     }
else
     start_agent;
fi</pre>
<p><strong>Installing Node and NPM</strong></p>
<p>You can just do:</p>
<pre>pacman -S nodejs</pre>
<p>If you&#8217;re OK with that version, which seems to track the Node releases pretty well.</p>
<p>Arch uses python3 as python. You need to change python to python2 (thanks <a href="http://www.robsearles.com/2011/02/11/nodejs-v0-4-0-on-arch-linux/">Rob Searles</a>!)</p>
<pre># node.js fix for arch (use python2) 
mkdir /tmp/bin
ln -s /usr/bin/python2 /tmp/bin/python
export PATH=/tmp/bin:$PATH</pre>
<p>You can then do a regular node install:</p>
<p>git clone git://github.com/joyent/node.git</p>
<p>git checkout v0.4.12</p>
<p>./configure</p>
<p>make</p>
<p>sudo make install</p>
<p>Remember to install npm as well:</p>
<pre>curl http://npmjs.org/install.sh | sudo sh</pre>
<p><strong>Installing my window manager and personal config</strong></p>
<pre>git clone git://github.com/mixu/nwm.git
cd nwm
node-waf clean || true &amp;&amp; node-waf configure build
sudo npm link # add a global npm symlink to this repository - so nwm-user can find it (man npm link)
cd ..
git clone git://github.com/mixu/nwm-user.git
cd nwm-user
npm link nwm # now make a symlink to the nwm installation</pre>
<p>Add it to ~/.xinitrc (change paths!!):</p>
<pre>exec /usr/local/bin/node ~/mnt/nwm-user/nwm-user.js 2&gt;~/nwm.err.log 1&gt;~/nwm.log</pre>
<p>And while we&#8217;re at it, lets add some other stuff:</p>
<pre>VBoxClient-all &amp;
export PATH=/tmp/bin:$PATH # for node-waf, too lazy to work on a better solution
xset +fp /usr/share/fonts/local
xset fp rehash</pre>
<p>Run &#8220;startx&#8221; to start X11 with nwm.</p>
<p><strong>Installing my mp3 player</strong></p>
<p>First, we need to configure alsa (included by default):</p>
<pre>pacman -S mpg123 alsa-utils</pre>
<p>Run:</p>
<pre>alsamixer</pre>
<p>and turn on Master and PCM channels (by pressing m) as they are muted by default.</p>
<pre>sudo alsactl store</pre>
<p>Then continue:</p>
<pre>git clone git://github.com/mixu/nplay.git</pre>
<p>Run nplay with</p>
<pre>node nplay.js</pre>
<p>TODO: fix directory in source code and change backend from mpg321 to mpg123.</p>
<p><strong>Switching the keyboard language in X11</strong></p>
<p>I sometimes need to write emails in Finnish, so here is how to switch the layout:</p>
<pre><code>setxkbmap -layout fi # revert back </code><span class="Apple-style-span" style="font-family: monospace;">setxkbmap -layout us</span><span class="Apple-style-span" style="font-family: monospace;"> </span></pre>
<p>Install yaourt</p>
<p>Install dependencies</p>
<p>yaourt libpng12 gtk2-theme-dust</p>
<p>&nbsp;</p>
<p><strong>Install Sublime Text 2</strong></p>
<p>Sublime Text needs libpng12, which you have to install from AUR:</p>
<pre>wget http://aur.archlinux.org/packages/li/libpng12/libpng12.tar.gz
tar -xzvf libpng12.tar.gz
cd libpng12
makepkg
pacman -U ./libpng12-1.2.46-2-x86_64.pkg.tar.xz</pre>
<p>Then download and run Sublime Text 2.</p>
<p>Also, you might want to ger http://aur.archlinux.org/packages/gt/gtk2-theme-dust/gtk2-theme-dust.tar.gz.</p>
<p><strong>Configuring Sublime Text 2</strong></p>
<pre>locate Packages # returns ~/.config/sublime-text-2/Packages
cd ~/.config/sublime-text-2/Packages
git clone https://github.com/buymeasoda/soda-theme/ "Theme - Soda"
cd User
wget http://blog.mixu.net/files/2010/05/my_themes.zip # Install my themes
unzip my_themes
rm my_themes.zip</pre>
<p><strong>Base File settings</strong></p>
<pre>{
  // FONTS and COLORS
  "color_scheme": "Packages/User/Mixu Espresso.tmTheme",
  "font_size": 11,
  "tab_size": 2,
  // WHITESPACE
    // Set to true to insert spaces when tab is pressed
    "translate_tabs_to_spaces": true,
    "trim_automatic_white_space": true,
    "trim_trailing_white_space_on_save": true,
    // Set to false to disable detection of tabs vs. spaces on load
    "detect_indentation": false,
  "shift_tab_unindent": true,
  // Set to false to disable highlighting any line with a caret
  "highlight_line": true,
  // Set to "none" to turn off drawing white space, "selection" to draw only the
  // white space within the selection, and "all" to draw all white space
  "draw_white_space": "selection",
  // Set to true to ensure the last line of the file ends in a newline
  // character when saving
  "ensure_newline_at_eof_on_save": true,
  "fold_buttons": false
}</pre>
<p><strong>Global Settings</strong></p>
<pre>{
  "theme": "Soda Light.sublime-theme"
}</pre>
<p><strong>Other tweaks</strong></p>
<p>I put these in my usual &#8220;startup&#8221; command, nwm-setup.sh and run it manually:</p>
<pre>xrandr --output VBOX0 --auto --left-of VBOX1 # Virtualbox displays
chromium &amp; # start chromium
export PS1="[\W]\$ "
xsetroot -cursor_name left_ptr # Set pointer
nitrogen --restore &amp; # Restore desktop background using nitrogen</pre>
<p><strong>Other dependencies</strong></p>
<pre>pacman -S redis mysql ruby libxslt</pre>
<p>Setting up ree:</p>
<pre>cd
bash &lt; &lt;(curl -s https://rvm.beginrescueend.com/install/rvm)
echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] &amp;&amp; . "$HOME/.rvm/scripts/rvm" # Load RVM function' &gt;&gt; ~/.bashrc
source .bashrc
rvm install ree-1.8.7-2011.03</pre>
<p>Installing REE will fail. <a href=" http://stackoverflow.com/questions/6134456/error-while-installing-ruby-1-8-7-on-fedora-15">You need to</a>run the installer from /home/m/.rvm/src/ree-1.8.7-2011.03/installer manually:</p>
<pre>./installer -no-tcmalloc</pre>
<p>Then continue on:</p>
<pre>rvm ree-1.8.7-2011.03 --default</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/11/10/my-arch-linux-setup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nginx, Websockets, SSL and Socket.IO deployment</title>
		<link>http://blog.mixu.net/2011/08/13/nginx-websockets-ssl-and-socket-io-deployment/</link>
		<comments>http://blog.mixu.net/2011/08/13/nginx-websockets-ssl-and-socket-io-deployment/#comments</comments>
		<pubDate>Sat, 13 Aug 2011 01:54:42 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1955</guid>
		<description><![CDATA[I&#8217;ve spent some time recently figuring out the options for deploying Websockets with SSL and load balancing &#8211; and more specifically, Socket.IO &#8211; while allowing for dual stacks (e.g. Node.js and another dev platform). Since there seems to be very little concrete guidance on this topic, here are my notes &#8211; I&#8217;d love to hear [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent some time recently figuring out the options for deploying Websockets with SSL and load balancing &#8211; and more specifically, Socket.IO &#8211; while allowing for dual stacks (e.g. Node.js and another dev platform). Since there seems to be very little concrete guidance on this topic, here are my notes &#8211; I&#8217;d love to hear from you on your implementation  (leave a comment or write about and link back)&#8230;</p>
<p><strong>The goal here is to:</strong></p>
<ol>
<li>Expose Socket.io and your main application from a single port &#8212; avoiding cross-domain communication</li>
<li>Support HTTPS for both connections &#8212; enabling secure messaging</li>
<li>Support the Websockets and Flashsockets transports from Socket.io &#8212; for performance</li>
<li>Perform load balancing for both the backends somewhere &#8212; for performance</li>
</ol>
<p><span style="font-size: 20px; font-weight: bold;">Socket.io&#8217;s various transports</span></p>
<p>Socket.io supports multiple different transports:</p>
<div>
<ul>
<li>WebSockets &#8212; which are essentially long lived HTTP 1.1 requests, which after a handshake upgrade to the Websockets protocol</li>
<li>Flash sockets &#8212; which are plain TCP sockets with optional SSL support (but Flash seems to use some older SSL encryption method)</li>
<li>various kinds of polling &#8212; which work over long lived HTTP 1.0 requests</li>
</ul>
</div>
<h2>Starting point: Nginx and Websockets</h2>
<p>Nginx is generally the first recommendation for Node.js deployments. It&#8217;s a high-performance server and even includes support for proxying requests via the <a href="http://wiki.nginx.org/NginxHttpProxyModule">HttpProxyModule</a>.</p>
<p>However, &#8212; and this should be made much obvious to people starting with Socket.io &#8212; the problem is that while Nginx can talk HTTP/1.1 to the client (browser), it talks HTTP/1.0 to the server. Nginx&#8217;s default HttpProxyModule does not support HTTP/1.1, which is needed for Websockets.</p>
<p>Websockets 76 requires support for HTTP/1.1 as the handshake mechanism is not compatible with HTTP/1.0. What this means is that if Nginx is used to reverse proxy a Websockets server (like Socket.io), then the WS connections will fail. So no Websockets for you if you&#8217;re behind Nginx.</p>
<p>There is a workaround, but I don&#8217;t see the benefit: use a TCP proxy (there is a <a href="https://github.com/yaoweibin/nginx_tcp_proxy_module">custom module for this by Weibin Yao</a>, <a href="http://www.letseehere.com/reverse-proxy-web-sockets">see here </a>). However, you cannot run another service on the same port (e.g. your main app and Socket.io on port 80) as the TCP proxy does not support routing based on the URL (e.g. /socket.io/ to Socket.io and the rest to the main app), only simple load balancing.</p>
<p>So the benefit gained from doing this is quite marginal: sure, you can use Nginx for load balancing, but you will still be working with alternative ports for your main app and Socket.io.</p>
<h2>Alternatives to Nginx</h2>
<p>Since you can&#8217;t use Nginx and support Websockets,  you&#8217;ll need to deal with two separate problems:</p>
<ol>
<li>How to terminate SSL connections and</li>
<li>How to route HTTP traffic to the right backend based on the URL / load balance</li>
</ol>
<p>If you want to run two services on the same port, then you will have to terminate SSL connections before doing anything else. There are several alternatives for SSL termination:</p>
<ul>
<li><a href="http://www.stunnel.org/">Stunnel</a>. Supports multiple SSL certificates per process, does simple SSL termination to another port.</li>
<li><a href="https://github.com/bumptech/stud">Stud</a>. Only supports one SSL certificate per invocation, does simple SSL termination to another port.</li>
<li><a href="http://www.apsis.ch/pound/">Pound</a>. An SSL-termination-capable reverse proxy and load balancer.</li>
<li>Node&#8217;s https. Can be made to do anything, but you&#8217;ll have to write it yourself.</li>
</ul>
<p>If you choose Stunnel or Stud, then you need a load balancer as well if you plan on having more than one Node instance in the backend.</p>
<p>HAProxy is not <em>generally compatible</em> with Websockets, but Socket.IO <span style="text-decoration: underline;">contains code which works around this issue</span> and allows you to use HAProxy. This means that the alternatives are:</p>
<ul>
<li>Stunnel for SSL termination + HAProxy for routing/load balancing</li>
<li>Stud for SSL termination + HAProxy for routing/load balancing</li>
<li>Pound (SSL and routing/load balancing)</li>
</ul>
<p>I haven&#8217;t looked into Pound more &#8211; mainly as I could not find info on it&#8217;s TCP reverse proxying capabilities (see the section on Flash sockets below), but <a href="http://the-rig.refinery29.com/post/7263057532/pound-and-varnish">it seems to work for these guys</a>.</p>
<h2>Setting up Stunnel</h2>
<p>The Stunnel part is quite simple:</p>
<pre>cert = /path/to/certfile.pem
; Service-level configuration
[https]
accept  = 443
connect = 8443</pre>
<p>If you only have one Node instance, you can skip setting up HAProxy, since you don&#8217;t need load balancing.</p>
<h2><strong>Setting up HAProxy</strong></h2>
<p><strong>Would you like Flash Sockets with that?</strong></p>
<p>Note that we need TCP mode in order to support Flash sockets, which do not speak HTTP.</p>
<p>Flash sockets are just plain and simple TCP sockets, which will start by sending the following payload: &#8216;&lt;policy-file-request/&gt;\0&#8242;. They expect to receive a Flash cross domain policy as a response.</p>
<p>Since Flash sockets don&#8217;t use HTTP, we need a load balancer which is capable of detecting the protocol of the request, and of forwarding non-HTTP requests to Socket.io.</p>
<p>HAProxy can do that, as it has two different modes of operation:</p>
<ul>
<li>HTTP mode &#8211; which allows you to specify the backend based on the URI</li>
<li>TCP mode &#8211; which can be used to load balance non-HTTP transports.</li>
</ul>
<p><strong>Main frontend</strong></p>
<p>We accept connections on two ports: 80 (HTTP) and 8443 (Stunnel-terminated HTTPS connections).</p>
<p>By default, everything goes to the backend app at port 3000. Some HTTP paths are selectively routed to socket.io</p>
<p>TCP mode is needed so that Flash socket connections can be passed through, and all non HTTP connections are sent to the TCP mode socket.io backend.<br />
<div id="wpshdo_1" class="wp-synhighlighter-outer"><div id="wpshdt_1" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_1"></a><a id="wpshat_1" class="wp-synhighlighter-title" href="#codesyntax_1"  onClick="javascript:wpsh_toggleBlock(1)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_1" onClick="javascript:wpsh_code(1)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_1" onClick="javascript:wpsh_print(1)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_1" class="wp-synhighlighter-inner" style="display: block;"><div class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># Main frontend</span><br />
frontend app<br />
&nbsp; <span style="color: #7a0874; font-weight: bold;">bind</span> 0.0.0.0:80<br />
&nbsp; <span style="color: #7a0874; font-weight: bold;">bind</span> 0.0.0.0:<span style="color: #000000;">8443</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># Mode is TCP</span><br />
&nbsp; mode tcp<br />
&nbsp; <span style="color: #666666; font-style: italic;"># allow for many connections, with long timeout</span><br />
&nbsp; maxconn <span style="color: #000000;">200000</span><br />
&nbsp; timeout client <span style="color: #000000;">86400000</span><br />
<br />
&nbsp; <span style="color: #666666; font-style: italic;"># default to webapp backend</span><br />
&nbsp; default_backend webapp<br />
<br />
&nbsp; <span style="color: #666666; font-style: italic;"># two URLs need to go to the node pubsub backend</span><br />
&nbsp; acl is_socket_io path_beg <span style="color: #000000; font-weight: bold;">/</span>node<br />
&nbsp; acl is_socket_io path_beg <span style="color: #000000; font-weight: bold;">/</span>socket.io<br />
&nbsp; &nbsp; &nbsp;use_backend socket_io <span style="color: #000000; font-weight: bold;">if</span> is_socket_io<br />
<br />
&nbsp; &nbsp;tcp-request inspect-delay 500ms<br />
&nbsp; &nbsp;tcp-request content accept <span style="color: #000000; font-weight: bold;">if</span> HTTP<br />
&nbsp; &nbsp;use_backend sio_tcp <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #000000; font-weight: bold;">!</span>HTTP</div></div></div></p>
<p><strong>Port 843: Flash policy</strong></p>
<p>Flash policy should be made available on 843.</p>
<div id="wpshdo_2" class="wp-synhighlighter-outer"><div id="wpshdt_2" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_2"></a><a id="wpshat_2" class="wp-synhighlighter-title" href="#codesyntax_2"  onClick="javascript:wpsh_toggleBlock(2)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_2" onClick="javascript:wpsh_code(2)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_2" onClick="javascript:wpsh_print(2)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_2" class="wp-synhighlighter-inner" style="display: block;"><div class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># Flash policy frontend</span><br />
frontend flashpolicy 0.0.0.0:<span style="color: #000000;">843</span><br />
&nbsp; &nbsp;mode tcp<br />
&nbsp; &nbsp;default_backend sio_tcp</div></div></div>
<p><strong>Default backend</strong></p>
<p>This is just for your main application.</p>
<div id="wpshdo_3" class="wp-synhighlighter-outer"><div id="wpshdt_3" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_3"></a><a id="wpshat_3" class="wp-synhighlighter-title" href="#codesyntax_3"  onClick="javascript:wpsh_toggleBlock(3)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_3" onClick="javascript:wpsh_code(3)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_3" onClick="javascript:wpsh_print(3)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_3" class="wp-synhighlighter-inner" style="display: block;"><div class="bash" style="font-family:monospace;">backend webapp<br />
&nbsp; &nbsp;mode http<br />
&nbsp; &nbsp;option httplog<br />
&nbsp; &nbsp;option httpclose<br />
&nbsp; &nbsp;server nginx1s localhost:<span style="color: #000000;">3000</span> check</div></div></div>
<p><strong>Socket.io backend</strong></p>
<p>Here, we have a bunch of settings in order to allow Websockets connections through HAProxy.</p>
<div id="wpshdo_4" class="wp-synhighlighter-outer"><div id="wpshdt_4" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_4"></a><a id="wpshat_4" class="wp-synhighlighter-title" href="#codesyntax_4"  onClick="javascript:wpsh_toggleBlock(4)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_4" onClick="javascript:wpsh_code(4)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_4" onClick="javascript:wpsh_print(4)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_4" class="wp-synhighlighter-inner" style="display: block;"><div class="bash" style="font-family:monospace;">backend socket_io<br />
&nbsp; mode http<br />
&nbsp; option &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;httplog<br />
&nbsp; <span style="color: #666666; font-style: italic;"># long timeout</span><br />
&nbsp; timeout server <span style="color: #000000;">86400000</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># check frequently to allow restarting</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># the node backend</span><br />
&nbsp; timeout check 1s<br />
&nbsp; <span style="color: #666666; font-style: italic;"># add X-Forwarded-For</span><br />
  &nbsp;option forwardfor<br />
&nbsp; <span style="color: #666666; font-style: italic;"># Do not use httpclose (= client and server</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># connections get closed), since it will close</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># Websockets connections</span><br />
&nbsp; no &nbsp; option httpclose<br />
&nbsp; <span style="color: #666666; font-style: italic;"># Use &quot;option http-server-close&quot; to preserve</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># client persistent connections while handling</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># every incoming request individually, dispatching</span><br />
&nbsp; <span style="color: #666666; font-style: italic;"># them one after another to servers, in HTTP close mode</span><br />
&nbsp; option http-server-close<br />
&nbsp; option forceclose<br />
&nbsp; <span style="color: #666666; font-style: italic;"># just one node server at :8000</span><br />
&nbsp; server node1 localhost:<span style="color: #000000;">8000</span> maxconn <span style="color: #000000;">2000</span> check</div></div></div>
<p><strong>Socket.io backend in TCP mode</strong></p>
<p>This is the same server as above, but accessed in TCP mode.</p>
<div id="wpshdo_5" class="wp-synhighlighter-outer"><div id="wpshdt_5" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_5"></a><a id="wpshat_5" class="wp-synhighlighter-title" href="#codesyntax_5"  onClick="javascript:wpsh_toggleBlock(5)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_5" onClick="javascript:wpsh_code(5)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_5" onClick="javascript:wpsh_print(5)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_5" class="wp-synhighlighter-inner" style="display: block;"><div class="bash" style="font-family:monospace;">backend sio_tcp<br />
&nbsp; mode tcp<br />
&nbsp; server node2 localhost:<span style="color: #000000;">8000</span> maxconn <span style="color: #000000;">2000</span> check</div></div></div>
<h2>Conclusion</h2>
<p>The configs above allow you to serve Websockets, Flash and polling from a single port.</p>
<p>However, I am dissatisfied by the complexity of this configuration. In particular, Flash sockets&#8217; TCP requirements are rather painful since they require protocol detection in order to work from a single port.</p>
<p>The alternative is of course to run Socket.io on a different port than your main app. This would mean that you configure HAProxy to just do TCP mode load balancing at that port, with SSL termination in front of HAProxy.</p>
<p>If you do that, you might want to configure a fallback from Nginx at port 80 to Socket.io for those clients who are behind draconian corporate firewalls which disallow ports other than 80 and 443. The fallback will only support long polling and I don&#8217;t think Socket.io itself supports automatically switching ports during transport negotiation, but you can detect a failure in Socket.io and re-initialize manually with a different port and polling-only transport.</p>
<p>Do you have a better way? How do you deploy Socket.io? Let me know in the comments below.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/08/13/nginx-websockets-ssl-and-socket-io-deployment/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Collaborative git reference</title>
		<link>http://blog.mixu.net/2011/08/06/collaborative-git-reference/</link>
		<comments>http://blog.mixu.net/2011/08/06/collaborative-git-reference/#comments</comments>
		<pubDate>Sat, 06 Aug 2011 03:11:02 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1977</guid>
		<description><![CDATA[Here is a basic reference for collaborative git commands: Checkout a remote branch # list branches first git branch -a # * master # remotes/origin/branch_name git checkout -b local_name remotes/origin/branch_name Merging # switch to master git checkout master # merge with experimental branch git merge experimental Create a tag # list tags git tag # [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a basic reference for collaborative git commands:</p>
<h2>Checkout a remote branch</h2>
<pre># list branches first
git branch -a
# * master
# remotes/origin/branch_name
git checkout -b local_name remotes/origin/branch_name</pre>
<h2>Merging</h2>
<pre># switch to master
git checkout master
# merge with experimental branch
git merge experimental</pre>
<h2>Create a tag</h2>
<pre># list tags
git tag
# add a tag
git tag tagname
# push to remote
git push origin master --tags</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/08/06/collaborative-git-reference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>dwm tips on Fedora</title>
		<link>http://blog.mixu.net/2011/06/11/dwm-tips-on-fedora/</link>
		<comments>http://blog.mixu.net/2011/06/11/dwm-tips-on-fedora/#comments</comments>
		<pubDate>Sat, 11 Jun 2011 20:49:24 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1885</guid>
		<description><![CDATA[I&#8217;ve been testing out Fedora 15&#8242;s Gnome 3 and Ubuntu&#8217;s Unity, and didn&#8217;t like either of them. They both take up too much precious screen space just to show a fancy UI, and requiring hardware acceleration is a pain for low end netbooks and virtual machines. So I decided to move to an alternative window [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been testing out Fedora 15&#8242;s Gnome 3 and Ubuntu&#8217;s Unity, and didn&#8217;t like either of them. They both take up too much precious screen space just to show a fancy UI, and requiring hardware acceleration is a pain for low end netbooks and virtual machines.</p>
<p>So I decided to move to an alternative window manager. DWM (dynamic window manager, <a href="http://dwm.suckless.org/">http://dwm.suckless.org/</a>) is an extremely lightweight tiling window manager written in C which saves screen space and works pretty well as long as you don&#8217;t need to connect to wireless networks.</p>
<p>I&#8217;ve been pretty happy with it. The main drawback is that connecting to wireless networks is a pain in the ass as there are no proper GUI tools to do this. Check out these tips to get started with dwm</p>
<h2>0. Installing dwm on Fedora, keyboard shortcuts</h2>
<p>To install DWM, run yum install dwm. You can then choose to use dwm or Gnome or Kde in the login screen.</p>
<p>The default keyboard shortcuts are listed at man dwm or at <a href="http://man.suckless.org/dwm/1/dwm">http://man.suckless.org/dwm/1/dwm</a>.</p>
<h2>1. Customizing dwm</h2>
<p>Customizing dwm can be done by making changes to config.h and recompiling the window manager.</p>
<p>Fedora has a really nice package called dwm-user, which automates this process! Here is the package description:</p>
<p><em>dwm-start is a helper script for running and reconfiguring dwm if neccessarry. It&#8217;s the preferred way of starting dwm in Fedora.</em><br />
<em>Running  dwm-start starts Fedora build by default. If you wish to customize your configuration, put the dwm config header file to $HOME/.dwm/config.h and adjust it according to your needs. Every time the user configuration file has changed, dwm-start will rebuild the user dwm binary prior to its execution.</em></p>
<p>All you need to do is:</p>
<pre>sudo yum install dwm-user</pre>
<pre>mkdir ~/.dwm</pre>
<pre>cp /usr/src/dwm-user-5.8.2-6.fc14/config.def.h ~/.dwm/config.h</pre>
<p>E.g. install via yum, then make a ~/.dwm folder, then copy the config.h file and edit it. When you restart, you can choose dwm-user as your window manager which uses you custom version of dwm. For example, I remapped Meta (Cmd/Windows key) + h and meta + l to meta + pg up / pg down and meta + shift + q to meta + shift + end since I&#8217;m currently running Fedora on an OSX host.</p>
<p>You will probably make changes to the keyboard shortcuts. To find the keymap:</p>
<pre>sudo updatedb</pre>
<pre>locate keysymdef.h</pre>
<p>Keysymdef.h lists the names of the keys in X11.</p>
<h2>2. Tip: Guake is just as awesome on dwm</h2>
<p>By default, dwm launches xterm. I prefer to use guake, since that allows me to get the tabbed terminal window on any workspace when I need them. Just launch guake&amp; to run it in the background.</p>
<p><strong>UPDATE</strong>: I moved to F15 (deciding simply to ignore Gnome 3) and noticed that guake has problems starting. To fix those:</p>
<pre>sudo yum install xfce4-notifyd</pre>
<p>Basically you need a notify daemon to allow Guake to print that pretty message &#8220;Guake is running&#8221;, and xfce4-notifyd provides an alternative notifications daemon.</p>
<h2>3. Launch netbeans and other Java programs with font smoothing and GTK look and feel</h2>
<p>You need to specify a couple of extra switches to get the GTK look and feel in Java programs, for example:</p>
<p>/home/username/netbeans-7.0/bin/netbeans -J-Dswing.aatext=true -J-Dawt.useSystemAAFontSettings=on &#8211;laf com.sun.java.swing.plaf.gtk.GTKLookAndFeel</p>
<h2>4. Launch nautilus without the desktop</h2>
<pre>nautilus --no-desktop</pre>
<h2>5. Use dwm with a dual screen setup</h2>
<p>If dwm starts with mirroring output to your secondary screen, then you need to run xrandr to get the names your screens. E.g. VBOX0 and VBOX1.</p>
<p>Then configure the screen layout:</p>
<pre>xrandr --output VBOX1 --auto --right-of VBOX0</pre>
<p>dwm will now let you have your own workspaces for each screen.</p>
<h2>6. Change your desktop background</h2>
<p>Use feh to change your desktop background:</p>
<pre>feh --bg-tile /path/to/background/image</pre>
<h2>7. xterm config</h2>
<p>For a usable xterm, create the following ~/.Xresources and run</p>
<div>
<pre><code>xrdb -merge .Xresources</code></pre>
</div>
<div id="wpshdo_6" class="wp-synhighlighter-outer"><div id="wpshdt_6" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_6"></a><a id="wpshat_6" class="wp-synhighlighter-title" href="#codesyntax_6"  onClick="javascript:wpsh_toggleBlock(6)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_6" onClick="javascript:wpsh_code(6)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_6" onClick="javascript:wpsh_print(6)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_6" class="wp-synhighlighter-inner" style="display: block;"><div class="bash" style="font-family:monospace;">xterm<span style="color: #000000; font-weight: bold;">*</span>faceName: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; monospace:<span style="color: #007800;">pixelsize</span>=14<br />
xterm<span style="color: #000000; font-weight: bold;">*</span>saveLines: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;9999<br />
xterm<span style="color: #000000; font-weight: bold;">*</span>scrollBar: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #c20cb9; font-weight: bold;">false</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>background: &nbsp;<span style="color: #666666; font-style: italic;">#000000</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>foreground: &nbsp;<span style="color: #666666; font-style: italic;">#dfdfdf</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color0: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#000000</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color1: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#9e1828</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color2: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#aece92</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color3: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#968a38</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color4: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#414171</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color5: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#963c59</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color6: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#418179</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color7: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#bebebe</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color8: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#666666</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color9: &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">#cf6171</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color10: &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">#c5f779</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color11: &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">#fff796</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color12: &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">#4186be</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color13: &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">#cf9ebe</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color14: &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">#71bebe</span><br />
xterm<span style="color: #000000; font-weight: bold;">*</span>color15: &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">#ffffff</span></div></div></div>
<h2>8. Add a clock using xsetroot</h2>
<p>You can do something like this in a bash script to show the time in dwm on the top right corner.</p>
<div>
<div>
<pre>
<pre>while true; do
   xsetroot -name "$( date +"%F %R" )"
   sleep 1m    # Update time every minute
done</pre>
</pre>
<h2>9. Connect to wifi</h2>
<p>This is rather painful. The instructions here were collected from the mailing list, and I did get them to work, but I&#8217;m too lazy to write a full tutorial on this right now.</p>
<p>Basically, you need to scan, then do different things depending on whether the wifi uses WEP or WPA for authentication.</p>
<p>Start by running:</p>
</div>
</div>
<pre>iwlist scan</pre>
<h2>9.1 WEP wifi</h2>
<pre>&gt; &gt; #wep connect to a wep wifi
&gt; &gt; #! /bin/sh
&gt; &gt;
&gt; &gt; key="`grep $1 /home/pmarin/wep | cut -d' ' -f2`"
&gt; &gt; sudo ifconfig wlan0 up
&gt; &gt; sudo iwconfig wlan0 essid $1
&gt; &gt; sudo iwconfig wlan0 key s:$key
&gt; &gt; sudo dhclient wlan0
&gt; &gt; #end</pre>
<pre>&gt; &gt; The wep is a plain file with to columms
&gt; &gt;
&gt; &gt; essid  key</pre>
<h2>9.2 WPA wifi</h2>
<pre>&gt; &gt;
&gt; &gt; #wpa connect to a wpa wifi
&gt; &gt; #! /bin/sh
&gt; &gt;
&gt; &gt; sudo ifconfig wlan0 up
&gt; &gt; sudo iwconfig wlan0 essid $1
&gt; &gt; sudo wpa_supplicant -iwlan0 -c/home/pmarin/wpa -B
&gt; &gt; sudo dhclient wlan0
&gt; &gt; #end
&gt; &gt;
&gt; &gt; the wpa file is similar than /etc/wpa_supplicant.conf</pre>
<p>To create the wpa file:</p>
<div>
<pre dir="ltr">wpa_passphrase your_ssid_of_network your_network_password</pre>
<pre dir="ltr">Create the file:</pre>
<pre dir="ltr">
<div>
<pre dir="ltr">ctrl_interface=/var/run/wpa_supplicant
#ap_scan=2

network={
       ssid="your_ssid"
       scan_ssid=1
       proto=WPA RSN
       key_mgmt=WPA-PSK
       pairwise=CCMP TKIP
       group=CCMP TKIP
       psk=your_psk_from_wpa_passphrase
}</pre>
</div>
<div>
<pre dir="ltr">sudo wpa_supplicant -Bw -Dwext -i eth0 -c/etc/wpa_supplicant.conf</pre>
</div>
</pre>
</div>
<h2>9.3 Wifi troubleshooting:</h2>
<p>1) CHECK THAT YOU DON&#8217;T have the NetworkManager service or wpa_supplicant running already!!!</p>
<p>You can run wpa_supplicant with -dd flag for a detailed debug output.1) If you don&#8217;t manage to connect to the AccessPoint, try to uncomment line 2 in /etc/wpa_supplicant.conf.</p>
<p>2) If that doesn&#8217;t help, try change its value to 0 or 1.</p>
<p>3) If you get troubles while authenticating, try removing &#8220;RSN&#8221; and/or&#8221;CCMP&#8221; strings from /etc/wpa_supplicant.conf.</p>
<p>Sources for Wifi stuff:</p>
<p><a href="http://ubuntuforums.org/showthread.php?t=263136">http://ubuntuforums.org/showthread.php?t=263136</a></p>
<p><a href="http://www.mail-archive.com/dwm@suckless.org/msg06800.html">http://www.mail-archive.com/dwm@suckless.org/msg06800.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/06/11/dwm-tips-on-fedora/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Quick tip: Fix Flash audio stutter on Fedora 14 (64bit)</title>
		<link>http://blog.mixu.net/2011/02/24/quick-tip-fix-flash-audio-stutter-on-fedora-14-64bit/</link>
		<comments>http://blog.mixu.net/2011/02/24/quick-tip-fix-flash-audio-stutter-on-fedora-14-64bit/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 15:16:37 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1817</guid>
		<description><![CDATA[On my FC14 machine, I had a problem with Flash (64bit) audio playback: the sound on sites other than Youtube would stutter terribly. It appears that this a systematic problem; but luckily there is a fix! Check out Ahmed Abdo&#8217;s post on Flash audio stutter for the details. Works perfectly for me! Details: https://bugzilla.redhat.com/show_bug.cgi?id=638477 The bug [...]]]></description>
			<content:encoded><![CDATA[<p>On my FC14 machine, I had a problem with Flash (64bit) audio playback: the sound on sites other than Youtube would stutter terribly. It appears that this a systematic problem; but luckily there is a fix!</p>
<p>Check out <a href="http://ahabdo.wordpress.com/2011/01/03/flash-64-bit-crappy-sound-fix-for-fedora-14/">Ahmed Abdo&#8217;s post on Flash audio stutter for the details</a>. Works perfectly for me!</p>
<p>Details: <a href="https://bugzilla.redhat.com/show_bug.cgi?id=638477">https://bugzilla.redhat.com/show_bug.cgi?id=638477</a> </p>
<p>The bug is triggered by a change in glibc. Who proposed the fix? <strong>Linus Torvalds</strong>. So I guess the following isn&#8217;t quite true?</p>
<p><img class="alignnone" title="xkcd" src="http://imgs.xkcd.com/comics/supported_features.png" alt="" width="324" height="326" /></p>
<p>I love the pragmatism from his part:</p>
<blockquote><p>
<em>So in the kernel we have a pretty strict &#8220;no regressions&#8221; rule, and that if people depend on interfaces we exported having side effects that weren&#8217;t intentional, we try to fix things so that they still work unless there is a major reason not to.</p>
<p>So I&#8217;m disappointed glibc just closes this as NOTABUG. There&#8217;s no real reason to do the copy backwards that I can see, so doing it that way is just stupid. </p>
<p>But whatever. You can do a LD_PRELOAD trick to get a sane memcpy(), and it does indeed fix the sound for me.<br />
[...]<br />
The fact that the glibc people don&#8217;t do that, and that this hasn&#8217;t been elevated despite clearly being a big usability problem (normal users SHOULD NOT HAVE TO google bugzillas and play with LD_PRELOAD to have a working system), is just sad.</em>
</p></blockquote>
<p>Although overall, as an end user it the conversation around this bug and its persistence makes me sad. I know it&#8217;s selfish not to care about the technical superiority of a solution or about who is to blame here &#8211; but I&#8217;d just like to have my smooth Flash playback&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/02/24/quick-tip-fix-flash-audio-stutter-on-fedora-14-64bit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HMVC -style cascading file loading in Node.js</title>
		<link>http://blog.mixu.net/2011/02/18/hmvc-style-cascading-file-loading-in-node-js/</link>
		<comments>http://blog.mixu.net/2011/02/18/hmvc-style-cascading-file-loading-in-node-js/#comments</comments>
		<pubDate>Fri, 18 Feb 2011 08:53:50 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1777</guid>
		<description><![CDATA[One of my favorite features of Kohana 3 is it&#8217;s cascading filesystem &#8211; so I decided to implement it for Node.js. A cascading filesystem is an elegant solution to a common problem: how to provide a mechanism for loading modules and reusing code? The following image from Kohana 3&#8242;s docs shows an example: Benefits The [...]]]></description>
			<content:encoded><![CDATA[<p>One of my favorite features of Kohana 3 is it&#8217;s cascading filesystem &#8211; so I decided to implement it for Node.js. A cascading filesystem is an elegant solution to a common problem: how to provide a mechanism for loading modules and reusing code?</p>
<p>The following image from Kohana 3&#8242;s docs shows an example:</p>
<p><a href="http://blog.mixu.net/files/2011/02/cascading_filesystem.png"><img title="cascading_filesystem" src="http://blog.mixu.net/files/2011/02/cascading_filesystem-223x300.png" alt="" width="223" height="300" /></a></p>
<h2>Benefits</h2>
<p>The key benefits are:</p>
<ol>
<li><strong>Consistency</strong>. All your application files, including views, controllers, models and other data such as translation messages are loaded using one, easy-to-understand mechanism.</li>
<li><strong>Easy reuse</strong>. Without a cascading file system, you&#8217;ll have to copy and move files around if you want to use someone else&#8217;s libraries or modules. With a cascading file system, you just place the module in your application, and enable cascading for that directory.</li>
<li><strong>Transparent extensibility</strong>. What if you want to override one part of a module (say, a view) but don&#8217;t want to modify your copy of the module (e.g. so that you can update without manually merging changes). A cascading filesystem allows you to selectively replace files in 3rd party code simply by providing your own version of the file.</li>
</ol>
<h2>The code</h2>
<ul>
<li><a href="https://github.com/mixu/hmvc-cfs">https://github.com/mixu/hmvc-cfs</a>/</li>
<li>It&#8217;s only about 90 lines of code, see <a href="https://github.com/mixu/hmvc-cfs/blob/master/index.js">this file</a></li>
</ul>
<h2>Load order and file name resolution</h2>
<p>The load order for my implementation is:</p>
<ol>
<li><strong>Application path</strong> &#8211;  files under ./application/ are always checked first.</li>
<li><strong>Module paths</strong> &#8211; set modules(['./modules/my-module']) to enable module loading. Files from modules are loaded from in the order they are added.</li>
<li><strong>System path</strong> &#8211; files under ./system/ are loaded if no alternative exists.</li>
</ol>
<p><strong>Assumptions about file and class names</strong></p>
<p>Files are assumed to be <strong><em>lowercase</em></strong>. <strong><em>Underscores in class names</em></strong> are replaced by slashes (so Controller_User becomes ./application/classes/ controller/user.js).</p>
<p><strong>Performance impact</strong></p>
<p>Requests are cached, so that additional calls to find_file() do not cause additional stat() calls in the filesystem. This is insignificant anyway, since Node.js servers are persistent so the cascading search is only done once per server instance for each file (not once per request).</p>
<p><strong>Loading 3rd party code</strong></p>
<p>The loaded files do not need to be &#8220;compatible&#8221; in any way other than layout in the file system. For example, while Hmvc.factory(&#8216;some_other_lib&#8217;) loads the file from ./application/ classes/some/other/lib.js, that file does not actually need to contain a class named some_other_lib; just that it returns something via module.exports.</p>
<h2>Methods</h2>
<p>The methods are:</p>
<ul>
<li>Hmvc.modules(['./modules/path-to-module']) &#8211; set the modules directories to search.</li>
<li>Hmvc.find_file(dir, file, ext) &#8211; Search each path under dir (e.g. &#8216;classes&#8217;, &#8216;views&#8217;) for file (filename) with the extension (ext, default is &#8220;.js&#8221;).</li>
<li>Hmvc.factory(class_name) &#8211; Return a new instance of the given class after loading the corresponding file from the cascading file system. Note that classes should be in the classes subdirectory.</li>
<li>Hmvc.load(class_name) &#8211; Return whatever require(file-which-contains-the-class) returns. Useful for extending classes, see below for an example.</li>
</ul>
<h2>Example usage:</h2>
<div id="wpshdo_7" class="wp-synhighlighter-outer"><div id="wpshdt_7" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_7"></a><a id="wpshat_7" class="wp-synhighlighter-title" href="#codesyntax_7"  onClick="javascript:wpsh_toggleBlock(7)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_7" onClick="javascript:wpsh_code(7)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_7" onClick="javascript:wpsh_print(7)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_7" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Hmvc <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'./hmvc.js'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #006600; font-style: italic;">// test class loading:</span><br />
<span style="color: #006600; font-style: italic;">// e.g. check ./application/classes/test.js</span><br />
<span style="color: #006600; font-style: italic;">// ./modules/modulename/classes/test.js</span><br />
<span style="color: #006600; font-style: italic;">// ./system/classes/test.js</span><br />
<span style="color: #003366; font-weight: bold;">var</span> t <span style="color: #339933;">=</span> Hmvc.<span style="color: #660066;">factory</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'test'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
t.<span style="color: #660066;">run</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #006600; font-style: italic;">// test view loading</span><br />
<span style="color: #006600; font-style: italic;">// e.g ./application/views/user/index.html</span><br />
<span style="color: #006600; font-style: italic;">// ./modules/modulename/views/user/index.html</span><br />
<span style="color: #006600; font-style: italic;">// ./system/views/user/index.html</span><br />
fs.<span style="color: #660066;">readFile</span><span style="color: #009900;">&#40;</span>Hmvc.<span style="color: #660066;">find_file</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'views'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'user/index'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'.html'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>err<span style="color: #339933;">,</span> data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">throw</span> err<span style="color: #339933;">;</span><br />
&nbsp; sys.<span style="color: #660066;">puts</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<p>To set modules:</p>
<div id="wpshdo_8" class="wp-synhighlighter-outer"><div id="wpshdt_8" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_8"></a><a id="wpshat_8" class="wp-synhighlighter-title" href="#codesyntax_8"  onClick="javascript:wpsh_toggleBlock(8)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_8" onClick="javascript:wpsh_code(8)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_8" onClick="javascript:wpsh_print(8)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_8" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// set only once, before calling any other functions!</span><br />
Hmvc.<span style="color: #660066;">modules</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #3366CC;">&quot;./modules/testmodule/&quot;</span><span style="color: #339933;">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #3366CC;">&quot;./modules/testmodule2/&quot;</span><span style="color: #339933;">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<h2>Extending classes:</h2>
<div id="wpshdo_9" class="wp-synhighlighter-outer"><div id="wpshdt_9" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_9"></a><a id="wpshat_9" class="wp-synhighlighter-title" href="#codesyntax_9"  onClick="javascript:wpsh_toggleBlock(9)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_9" onClick="javascript:wpsh_code(9)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_9" onClick="javascript:wpsh_print(9)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_9" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// test extending class (see code in /application/classes/controller/extend.js</span><br />
<span style="color: #006600; font-style: italic;">// to see how extension is achieved)</span><br />
<span style="color: #006600; font-style: italic;">// e.g. ./application/classes/controller/extend.js</span><br />
<span style="color: #006600; font-style: italic;">// ./modules/modulename/classes/controller/extend.js</span><br />
<span style="color: #006600; font-style: italic;">// ./system/classes/controller/extend.js</span><br />
<span style="color: #003366; font-weight: bold;">var</span> t3 <span style="color: #339933;">=</span> Hmvc.<span style="color: #660066;">factory</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Controller_Extend'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
t3.<span style="color: #660066;">run</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
t3.<span style="color: #660066;">run_parent</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<p>Note that if you put hmvc.js in ~/node_modules/hmvc.js, you don&#8217;t need to specify the path to hmvc.js&#8230; see Modules in node.js docs.</p>
<div id="wpshdo_10" class="wp-synhighlighter-outer"><div id="wpshdt_10" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_10"></a><a id="wpshat_10" class="wp-synhighlighter-title" href="#codesyntax_10"  onClick="javascript:wpsh_toggleBlock(10)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_10" onClick="javascript:wpsh_code(10)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_10" onClick="javascript:wpsh_print(10)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_10" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// in extend.js:</span><br />
<span style="color: #003366; font-weight: bold;">var</span> Controller_Extend <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
<span style="color: #009900;">&#125;</span><br />
<span style="color: #006600; font-style: italic;">// extend the class</span><br />
<span style="color: #003366; font-weight: bold;">var</span> util <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'util'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> Hmvc <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'../../../../hmvc.js'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
util.<span style="color: #660066;">inherits</span><span style="color: #009900;">&#40;</span>Controller_Extend<span style="color: #339933;">,</span> Hmvc.<span style="color: #660066;">load</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Controller_Base'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
Controller_Extend.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">run</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Controller_Extend from testmodule2.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
Controller_Extend.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">run_parent</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #006600; font-style: italic;">// run the parent function</span><br />
&nbsp; &nbsp;Controller_Extend.<span style="color: #660066;">super_</span>.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">run</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<br />
module.<span style="color: #660066;">exports</span> <span style="color: #339933;">=</span> Controller_Extend<span style="color: #339933;">;</span></div></div></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/02/18/hmvc-style-cascading-file-loading-in-node-js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Javascript, node.js and for loops</title>
		<link>http://blog.mixu.net/2011/02/03/javascript-node-js-and-for-loops/</link>
		<comments>http://blog.mixu.net/2011/02/03/javascript-node-js-and-for-loops/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 23:00:23 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1653</guid>
		<description><![CDATA[What does this code print out? Assume that console.log logs to the console. Experiment #1: For loop 0, 1, 2, 3, 4 - easy, right? What about this code? Experiment #2: setTimeout The result is 5, 5, 5, 5, 5.What about this? Experiment #3: Callback function 0, 1, 2, 3, 4 &#8212; right? (Yup.) And this? [...]]]></description>
			<content:encoded><![CDATA[<p>What does this code print out? Assume that console.log logs to the console.</p>
<p><strong>Experiment #1: For loop</strong></p>
<div id="wpshdo_11" class="wp-synhighlighter-outer"><div id="wpshdt_11" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_11"></a><a id="wpshat_11" class="wp-synhighlighter-title" href="#codesyntax_11"  onClick="javascript:wpsh_toggleBlock(11)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_11" onClick="javascript:wpsh_code(11)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_11" onClick="javascript:wpsh_print(11)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_11" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'For loop'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp;console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>0, 1, 2, 3, 4 - easy, right? What about this code?</p>
<p><strong>Experiment #2: setTimeout</strong></p>
<div id="wpshdo_12" class="wp-synhighlighter-outer"><div id="wpshdt_12" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_12"></a><a id="wpshat_12" class="wp-synhighlighter-title" href="#codesyntax_12"  onClick="javascript:wpsh_toggleBlock(12)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_12" onClick="javascript:wpsh_code(12)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_12" onClick="javascript:wpsh_print(12)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_12" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'setTimeout'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; setTimeout<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'st:'</span><span style="color: #339933;">+</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 0<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>The result is 5, 5, 5, 5, 5.What about this?</p>
<p><strong>Experiment #3: Callback function</strong></p>
<div id="wpshdo_13" class="wp-synhighlighter-outer"><div id="wpshdt_13" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_13"></a><a id="wpshat_13" class="wp-synhighlighter-title" href="#codesyntax_13"  onClick="javascript:wpsh_toggleBlock(13)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_13" onClick="javascript:wpsh_code(13)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_13" onClick="javascript:wpsh_print(13)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_13" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> wrap<span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; callback<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Simple wrap'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; wrap<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>0, 1, 2, 3, 4 &#8212; right? (Yup.) And this?</p>
<p><strong>Experiment #4: While loop emulating sleep</strong></p>
<div id="wpshdo_14" class="wp-synhighlighter-outer"><div id="wpshdt_14" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_14"></a><a id="wpshat_14" class="wp-synhighlighter-title" href="#codesyntax_14"  onClick="javascript:wpsh_toggleBlock(14)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_14" onClick="javascript:wpsh_code(14)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_14" onClick="javascript:wpsh_print(14)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_14" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> sleep<span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #003366; font-weight: bold;">var</span> now <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> now <span style="color: #339933;">+</span> <span style="color: #CC0000;">1000</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #006600; font-style: italic;">// do nothing</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; callback<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Sleep'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; sleep<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>0, 1, 2, 3, 4. And this?</p>
<p><strong>Experiment #5: Node.js process.nextTick</strong></p>
<div id="wpshdo_15" class="wp-synhighlighter-outer"><div id="wpshdt_15" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_15"></a><a id="wpshat_15" class="wp-synhighlighter-title" href="#codesyntax_15"  onClick="javascript:wpsh_toggleBlock(15)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_15" onClick="javascript:wpsh_code(15)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_15" onClick="javascript:wpsh_print(15)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_15" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'nextTick'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp;process.<span style="color: #660066;">nextTick</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'nt:'</span><span style="color: #339933;">+</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>Well&#8230; it&#8217;s 5, 5, 5, 5, 5.</p>
<p><strong>Experiment #6: Delayed calls</strong></p>
<div id="wpshdo_16" class="wp-synhighlighter-outer"><div id="wpshdt_16" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_16"></a><a id="wpshat_16" class="wp-synhighlighter-title" href="#codesyntax_16"  onClick="javascript:wpsh_toggleBlock(16)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_16" onClick="javascript:wpsh_code(16)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_16" onClick="javascript:wpsh_print(16)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_16" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> data <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; data<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> foo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
data<span style="color: #009900;">&#91;</span>0<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> data<span style="color: #009900;">&#91;</span>1<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> data<span style="color: #009900;">&#91;</span>2<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> data<span style="color: #009900;">&#91;</span>3<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> data<span style="color: #009900;">&#91;</span>4<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<p>Again, 5, 5, 5, 5, 5.</p>
<h2><strong>Ok, I&#8217;m confused. Why does this happen?</strong></h2>
<p>Looking at experiments #1 to #6, you can see a pattern emerge: delayed calls, whether they are via setTimeout(), Node.js-specific process.nextTick() or a simple array of functions all print the unexpected result &#8220;5&#8243;.</p>
<p>Fundamentally, the only thing that matters is<strong> at what time the function code is executed</strong>. setTimeout() and process.nextTick() ensure that the function is only executed at some later stage. Similarly, assigning functions into an array explicitly like in Experiment #6 means that the code within the function is only executed after the loop has been completed.</p>
<p>There are three things you need to remember about Javascript:</p>
<ol>
<li>Variable scope is based on the nesting of functions. In other words, the position of the function in the source always determines what variables can be accessed; nested functions can access their parent&#8217;s variables, non-nested functions can only access the topmost, global variables.</li>
<li>Functions can create new scopes; the default behavior is to access previous scope.</li>
<li>Some functions have the side-effect of being event-driven and executed later, rather than immediately. You can emulate this yourself by storing but not executing functions, see Experiment #6.</li>
</ol>
<p>What we would expect, based on experience in other languages, is that in the for loop, calling the function would result in a call-by-value (since we are passing a primitive &#8211; an integer) and that function calls would run using a copy of that value at the time when the part of the code was &#8220;passed over&#8221; (e.g. when the surrounding code was executed). That&#8217;s not what happens:</p>
<p><strong>A</strong><strong> nested</strong><strong> function does not get a copy of the value of the variable &#8212; it gets a live reference to the variable itself and can access it at a much later stage.</strong> So while the reference to <em>i</em> is valid in both experiment 2, 5, and 6 they refer to the value of i at the time of their execution &#8211; which is on the next event loop &#8211; which is after the loop has run &#8211; which is why they get the value 5.</p>
<p><strong>Functions <span style="text-decoration: underline;">can</span> create new scopes but they do not have to.</strong> The default behavior allows us to refer back to the previous scope (all the way up to the global scope); this is why code executing at a later stage can still access i. Because no variable <em>i </em>exists in the current scope, the <em>i </em>from the parent scope is used; because the parent has already executed, the value of <em>i</em> is 5.</p>
<p>Hence, we can fix the problem by explicitly establishing a new scope every time the loop is executed; then referring back to that new inner scope later.  The only way to do this is to use an (anonymous) function plus explicitly defining a variable in that scope. There are two ways to do this:</p>
<p>Option 1) We can allow the value of i to &#8220;leak&#8221; from the previous scope, but explicitly establish a new variable j in the new scope to hold that value for future execution of nested functions:</p>
<p><strong>Experiment #7: Closure with new scope establishing a new variable</strong></p>
<div id="wpshdo_17" class="wp-synhighlighter-outer"><div id="wpshdt_17" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_17"></a><a id="wpshat_17" class="wp-synhighlighter-title" href="#codesyntax_17"  onClick="javascript:wpsh_toggleBlock(17)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_17" onClick="javascript:wpsh_code(17)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_17" onClick="javascript:wpsh_print(17)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_17" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'new scope nexttick with value binding in new func scope'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp;<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #003366; font-weight: bold;">var</span> j <span style="color: #339933;">=</span> i<span style="color: #339933;">;</span><br />
&nbsp; process.<span style="color: #660066;">nextTick</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'nexttick-new-scope-new-bind:'</span><span style="color: #339933;">+</span>j<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp;<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>Resulting in 0, 1, 2, 3, 4. Accessing j returns the value of i at the time when the closure was executed &#8211; and as you can see, we are immediately executing the function by appending ();</p>
<p>We need to have that wrapping function, because only functions establish new scope. In fact, we are establishing five new scopes when the loop is run, each iteration creating a scope with its own, separate variable j with a different value (0, 1, 2, 3, 4); each accessible from the inner closure at the time the code in it is run. Without the wrapping closure the reference to j in the innermost closure would end up having the same scope as i; it would then have the value of i at the time of the execution; which would be 5.</p>
<p>Options 2: Or we can pass the value to the new scope as a parameter:</p>
<p><strong>Experiment #8: Settimeout in closure with new scope</strong></p>
<div id="wpshdo_18" class="wp-synhighlighter-outer"><div id="wpshdt_18" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_18"></a><a id="wpshat_18" class="wp-synhighlighter-title" href="#codesyntax_18"  onClick="javascript:wpsh_toggleBlock(18)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_18" onClick="javascript:wpsh_code(18)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_18" onClick="javascript:wpsh_print(18)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_18" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'new scope'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp;<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; setTimeout<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'st2:'</span><span style="color: #339933;">+</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 0<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp;<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>Resulting in 0, 1, 2, 3, 4.</p>
<p>Now you should remember one more rule to understand the second solution:</p>
<ul>
<li>Functions can be passed as data; they are only evaluated when explicitly evaluated (e.g. by appending () or by using function.call or function.apply).</li>
</ul>
<p>So when we have (function(param))(param), we are calling the function immediately and parameters always establish a new variable/identifier in the function scope; that allows us to use the i from the new scope  in our delayed function call &#8211; since it is bound to the parameter, not to the parent scope.</p>
<p>This also means that this does NOT work (process.nextTick is interchangeable with setTimeout):</p>
<p><strong>Experiment #9: Closure with new scope containing callback triggered on process.nextTick</strong></p>
<div id="wpshdo_19" class="wp-synhighlighter-outer"><div id="wpshdt_19" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_19"></a><a id="wpshat_19" class="wp-synhighlighter-title" href="#codesyntax_19"  onClick="javascript:wpsh_toggleBlock(19)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_19" onClick="javascript:wpsh_code(19)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_19" onClick="javascript:wpsh_print(19)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_19" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'new scope nexttick'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp;<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; process.<span style="color: #660066;">nextTick</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'nexttick-new-scope:'</span><span style="color: #339933;">+</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp;<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>5, 5, 5, 5, 5 &#8211; since i still refers to the old scope. Compare that with experiment #7, where while the inner code is the same, we actually establish a new variable in the wrapping closure&#8217;s scope, which is then referred to by the inner code.</p>
<p><strong>Conclusion</strong></p>
<p>I should note that this has nothing do to with synchronicity or asynchronicity; it is simply the way in which scope resolution works for Javascript when code execution is delayed in some manner while referring to variables defined in the parent scope of the nested code.</p>
<p>In Javascript, all functions store &#8220;a hierarchical chain of all parent variable objects, which are above the current function context; the chain is saved to the function at its creation&#8221;. Because the scope chain is stored at creation, it is static and the relative nesting of functions precisely determines variable scope. When scope resolution occurs during code execution, the value for a particular identifier such as i is searched from:</p>
<ol>
<li>first from the parameters given to the function (a.k.a. the activation object)</li>
<li>and then from the statically stored chain of scopes (stored as the function&#8217;s internal property on creation) from top (e.g. parent) to bottom (e.g. global scope).</li>
</ol>
<p>Javascript will keep the full set of variables of each of the statically stored chains accessible even after their execution has completed, storing them in what is called a variable object. Since code that executes later will receive the value in the variable object at that later time, variables referring to the parent scope of nested code end up having &#8220;unexpected&#8221; results unless we create a new scope when the parent is run, copy the value from the parent to a variable in that new scope and refer to the variable in the new scope.</p>
<p>For a much more detailed explanation, please read Dimitry Soshnikov&#8217;s <a href="http://dmitrysoshnikov.com/ecmascript/javascript-the-core/">detailed account of ECMA-262</a> which explains these things in full detail; in particular about <a href="http://dmitrysoshnikov.com/ecmascript/chapter-4-scope-chain/">Scope chains</a> and <a href="http://dmitrysoshnikov.com/ecmascript/chapter-8-evaluation-strategy/">Evaluation strategies</a>. His explanations of the details are the best I&#8217;ve seen anywhere!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/02/03/javascript-node-js-and-for-loops/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Essential Node.js patterns and snippets</title>
		<link>http://blog.mixu.net/2011/02/02/essential-node-js-patterns-and-snippets/</link>
		<comments>http://blog.mixu.net/2011/02/02/essential-node-js-patterns-and-snippets/#comments</comments>
		<pubDate>Tue, 01 Feb 2011 22:28:12 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1490</guid>
		<description><![CDATA[In this post, I take a look at the different patterns that you need to know when using Node.js. These came from my own coding and from a look at the code behind Tim Caswell&#8217;s flow control libraries. I think it is necessary to know how these basic patterns are implemented even if you use [...]]]></description>
			<content:encoded><![CDATA[<p>In this post, I take a look at the different patterns that you need to know when using Node.js. These came from my own coding and from a look at the code behind Tim Caswell&#8217;s flow control libraries. I think it is necessary to know how these basic patterns are implemented even if you use a library..</p>
<h1>1. Objects and classes</h1>
<h2><strong>1.1 Class pattern</strong></h2>
<div id="wpshdo_20" class="wp-synhighlighter-outer"><div id="wpshdt_20" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_20"></a><a id="wpshat_20" class="wp-synhighlighter-title" href="#codesyntax_20"  onClick="javascript:wpsh_toggleBlock(20)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_20" onClick="javascript:wpsh_code(20)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_20" onClick="javascript:wpsh_print(20)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_20" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Constructor</span><br />
<span style="color: #003366; font-weight: bold;">var</span> <span style="color: #003366; font-weight: bold;">Class</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>value1<span style="color: #339933;">,</span> value2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">value1</span> <span style="color: #339933;">=</span> value1<span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
<span style="color: #006600; font-style: italic;">// properties and methods</span><br />
<span style="color: #003366; font-weight: bold;">Class</span>.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; value1<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;default_value&quot;</span><span style="color: #339933;">,</span><br />
&nbsp; method<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>argument<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">value2</span> <span style="color: #339933;">=</span> argument <span style="color: #339933;">+</span> <span style="color: #CC0000;">100</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<span style="color: #006600; font-style: italic;">// node.js module export</span><br />
module.<span style="color: #660066;">exports</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">Class</span><span style="color: #339933;">;</span><br />
<span style="color: #006600; font-style: italic;">// constructor call</span><br />
<span style="color: #003366; font-weight: bold;">var</span> object <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> <span style="color: #003366; font-weight: bold;">Class</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Hello&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<p>If the class is long, then instead of doing a single Class.prototype = {&#8230;} assignment, it may be split into multiple Class.prototype.method = function () {..} assignments.</p>
<p><strong><span style="text-decoration: underline;">Reminder</span></strong>: Assign all your properties some value in your constructor. Otherwise while the resulting object can access the property defined in the prototype, the prototype value is <em>shared among all instances</em>. So in order for your &#8220;instance&#8221; to actually own it&#8217;s own copies, you have to explicitly initialize the variables in the constructor, or they will act like static variables in non-prototype-based OOP. It&#8217;s a stupid mistake, don&#8217;t make it.</p>
<h2>1.2 Accessing global values from objects</h2>
<div id="wpshdo_21" class="wp-synhighlighter-outer"><div id="wpshdt_21" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_21"></a><a id="wpshat_21" class="wp-synhighlighter-title" href="#codesyntax_21"  onClick="javascript:wpsh_toggleBlock(21)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_21" onClick="javascript:wpsh_code(21)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_21" onClick="javascript:wpsh_print(21)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_21" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// constructor</span><br />
<span style="color: #003366; font-weight: bold;">var</span> <span style="color: #003366; font-weight: bold;">Class</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>global<span style="color: #339933;">,</span> value2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">global</span> <span style="color: #339933;">=</span> global<span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
<span style="color: #006600; font-style: italic;">// access using this.global in class methods</span></div></div></div>
<h2>1.3 Factory pattern</h2>
<div id="wpshdo_22" class="wp-synhighlighter-outer"><div id="wpshdt_22" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_22"></a><a id="wpshat_22" class="wp-synhighlighter-title" href="#codesyntax_22"  onClick="javascript:wpsh_toggleBlock(22)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_22" onClick="javascript:wpsh_code(22)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_22" onClick="javascript:wpsh_print(22)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_22" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Constructor</span><br />
<span style="color: #003366; font-weight: bold;">var</span> <span style="color: #003366; font-weight: bold;">Class</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>value1<span style="color: #339933;">,</span> value2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> ... <span style="color: #009900;">&#125;</span><br />
<span style="color: #006600; font-style: italic;">// Factory</span><br />
<span style="color: #003366; font-weight: bold;">Class</span>.<span style="color: #660066;">factory</span><span style="color: #009900;">&#40;</span>value1<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span> <span style="color: #003366; font-weight: bold;">Class</span><span style="color: #009900;">&#40;</span>value1<span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;aaa&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><br />
<span style="color: #006600; font-style: italic;">// properties and methods</span><br />
<span style="color: #003366; font-weight: bold;">Class</span>.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> ... <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></div></div></div></pre>
<h2>1.4 Sharing state between modules</h2>
<p><div id="wpshdo_23" class="wp-synhighlighter-outer"><div id="wpshdt_23" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_23"></a><a id="wpshat_23" class="wp-synhighlighter-title" href="#codesyntax_23"  onClick="javascript:wpsh_toggleBlock(23)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_23" onClick="javascript:wpsh_code(23)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_23" onClick="javascript:wpsh_print(23)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_23" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">Common <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; util<span style="color: #339933;">:</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'util'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><br />
&nbsp; fs<span style="color: #339933;">:</span> &nbsp; require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'fs'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><br />
&nbsp; path<span style="color: #339933;">:</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'path'</span><span style="color: #009900;">&#41;</span><br />
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<br />
module.<span style="color: #660066;">exports</span> <span style="color: #339933;">=</span> Common<span style="color: #339933;">;</span><br />
<br />
<span style="color: #006600; font-style: italic;">// in other modules</span><br />
<span style="color: #003366; font-weight: bold;">var</span> Common <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'./common.js'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<h2>1.5 Singleton class (added Feb 2011)</h2>
<div id="wpshdo_24" class="wp-synhighlighter-outer"><div id="wpshdt_24" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_24"></a><a id="wpshat_24" class="wp-synhighlighter-title" href="#codesyntax_24"  onClick="javascript:wpsh_toggleBlock(24)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_24" onClick="javascript:wpsh_code(24)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_24" onClick="javascript:wpsh_print(24)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_24" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Singleton <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">var</span> private_variable <span style="color: #339933;">=</span> <span style="color: #3366CC;">'value'</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> private_function<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; ...<br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> public_function<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; ...<br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
&nbsp; <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; public_function<span style="color: #339933;">:</span> public_function<br />
&nbsp; <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<h1>2. Parsing requests</h1>
<h2>2.1 Parsing GET</h2>
<div id="wpshdo_25" class="wp-synhighlighter-outer"><div id="wpshdt_25" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_25"></a><a id="wpshat_25" class="wp-synhighlighter-title" href="#codesyntax_25"  onClick="javascript:wpsh_toggleBlock(25)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_25" onClick="javascript:wpsh_code(25)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_25" onClick="javascript:wpsh_print(25)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_25" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// parse URL</span><br />
<span style="color: #003366; font-weight: bold;">var</span> url_parts <span style="color: #339933;">=</span> url.<span style="color: #660066;">parse</span><span style="color: #009900;">&#40;</span>req.<span style="color: #660066;">url</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #006600; font-style: italic;">// parse query</span><br />
<span style="color: #003366; font-weight: bold;">var</span> raw <span style="color: #339933;">=</span> querystring.<span style="color: #660066;">parse</span><span style="color: #009900;">&#40;</span>url_parts.<span style="color: #660066;">query</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #006600; font-style: italic;">// some juggling e.g. for data from jQuery ajax() calls.</span><br />
<span style="color: #003366; font-weight: bold;">var</span> data <span style="color: #339933;">=</span> raw <span style="color: #339933;">?</span> raw <span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
data <span style="color: #339933;">=</span> raw.<span style="color: #660066;">data</span> <span style="color: #339933;">?</span> JSON.<span style="color: #660066;">parse</span><span style="color: #009900;">&#40;</span>raw.<span style="color: #660066;">data</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> data<span style="color: #339933;">;</span></div></div></div>
<h2>2.2 Parsing POST</h2>
<div id="wpshdo_26" class="wp-synhighlighter-outer"><div id="wpshdt_26" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_26"></a><a id="wpshat_26" class="wp-synhighlighter-title" href="#codesyntax_26"  onClick="javascript:wpsh_toggleBlock(26)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_26" onClick="javascript:wpsh_code(26)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_26" onClick="javascript:wpsh_print(26)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_26" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>req.<span style="color: #660066;">method</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'POST'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">var</span> fullBody <span style="color: #339933;">=</span> <span style="color: #3366CC;">''</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;req.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'data'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>chunk<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #006600; font-style: italic;">// append the current chunk of data to the fullBody variable</span><br />
&nbsp; &nbsp;fullBody <span style="color: #339933;">+=</span> chunk.<span style="color: #660066;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;req.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'end'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// parse the received body data</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #003366; font-weight: bold;">var</span> decodedBody <span style="color: #339933;">=</span> querystring.<span style="color: #660066;">parse</span><span style="color: #009900;">&#40;</span>fullBody<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>decodedBody<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<h1>3. Concurrency</h1>
<h2>3.1 Waiting for async stuff to complete before continuing</h2>
<p>E.g. when you need to have all the results from the database before you do something.</p>
<div id="wpshdo_27" class="wp-synhighlighter-outer"><div id="wpshdt_27" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_27"></a><a id="wpshat_27" class="wp-synhighlighter-title" href="#codesyntax_27"  onClick="javascript:wpsh_toggleBlock(27)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_27" onClick="javascript:wpsh_code(27)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_27" onClick="javascript:wpsh_print(27)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_27" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> wait <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>callbacks<span style="color: #339933;">,</span> done<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">var</span> counter <span style="color: #339933;">=</span> callbacks.<span style="color: #660066;">length</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">var</span> next <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">--</span>counter <span style="color: #339933;">==</span> 0<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;done<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> callbacks.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; callbacks<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>Example usage (if you prefer, imagine that these are three database calls and that you are storing the results in some higher-scope variable in each of them and then using that result in function d):</p>
<div id="wpshdo_28" class="wp-synhighlighter-outer"><div id="wpshdt_28" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_28"></a><a id="wpshat_28" class="wp-synhighlighter-title" href="#codesyntax_28"  onClick="javascript:wpsh_toggleBlock(28)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_28" onClick="javascript:wpsh_code(28)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_28" onClick="javascript:wpsh_print(28)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_28" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> a <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
   setTimeout<span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
      console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Done A&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
      next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
   <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 3000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #003366; font-weight: bold;">var</span> b <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
   setTimeout<span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
      console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Done B&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
      next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
   <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 2000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #003366; font-weight: bold;">var</span> c <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
   setTimeout<span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
      console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Done C&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
      next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
   <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 1000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #003366; font-weight: bold;">var</span> d <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
   console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;All done!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
<br />
wait<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>a<span style="color: #339933;">,</span> b<span style="color: #339933;">,</span> c<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> d <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<p>Similar libraries include: Tim Caswell&#8217;s <a href="https://github.com/creationix/step">Step </a>and Will Conant&#8217;s <a href="https://github.com/willconant/flow-js">Flow</a>.exec(). This code is simpler so it doesn&#8217;t use<em> this</em> to pass the function next(); but rather passes it explicitly. Also it needs an array, instead of accepting an arbitrary number of function arguments. The library functions do better error handling and have more features, so you might want to use them / look at them to improve the code.</p>
<h2>3.2 Limiting concurrency</h2>
<p>E.g. reading a gazillion files but just running 30 reads at a time not to exhaust the available file handles. You have a list of operations to do, you want to do them all but can&#8217;t start/don&#8217;t want to have more than max_concurrency number of the operations running simultaneously.</p>
<p>I call this the Pile, but there probably is a better name for it. Put your stuff in the pile, and then run it all, finally call done() when everything is done. Main difference with simple completion counters like Wait() above is that this code limits concurrent execution, which is necessary in some cases (e.g. reading files).</p>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;"><div id="wpshdo_29" class="wp-synhighlighter-outer"><div id="wpshdt_29" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_29"></a><a id="wpshat_29" class="wp-synhighlighter-title" href="#codesyntax_29"  onClick="javascript:wpsh_toggleBlock(29)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_29" onClick="javascript:wpsh_code(29)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_29" onClick="javascript:wpsh_print(29)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_29" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Pile <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">pile</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">concurrency</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">done</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">max_concurrency</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">10</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
Pile.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; add<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">pile</span>.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span><br />
&nbsp; run<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>done<span style="color: #339933;">,</span> max_concurrency<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">done</span> <span style="color: #339933;">=</span> done <span style="color: #339933;">||</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">done</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">max_concurrency</span> <span style="color: #339933;">=</span> max_concurrency <span style="color: #339933;">||</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">max_concurrency</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #003366; font-weight: bold;">var</span> target <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">pile</span>.<span style="color: #660066;">length</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #003366; font-weight: bold;">var</span> that <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #003366; font-weight: bold;">var</span> next <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;that.<span style="color: #660066;">concurrency</span><span style="color: #339933;">--;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#40;</span><span style="color: #339933;">--</span>target <span style="color: #339933;">==</span> 0 <span style="color: #339933;">?</span> that.<span style="color: #660066;">done</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> that.<span style="color: #660066;">run</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">concurrency</span> <span style="color: #339933;">&lt;</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">max_concurrency</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">pile</span>.<span style="color: #660066;">length</span> <span style="color: #339933;">&gt;</span> 0<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">concurrency</span><span style="color: #339933;">++;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">var</span> callback <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">pile</span>.<span style="color: #660066;">shift</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;callback<span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></div></div></div></p>
<p>Example usage (add 20 functions, then run em at concurrency of 5 at a time). Again, imagine that setTimeout an async I/O call.</p>
<p><strong>Note:</strong> you have to call next() when you&#8217;re done.</p>
<div id="wpshdo_30" class="wp-synhighlighter-outer"><div id="wpshdt_30" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_30"></a><a id="wpshat_30" class="wp-synhighlighter-title" href="#codesyntax_30"  onClick="javascript:wpsh_toggleBlock(30)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_30" onClick="javascript:wpsh_code(30)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_30" onClick="javascript:wpsh_print(30)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_30" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">pilex <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Pile<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #003366; font-weight: bold;">var</span> counter <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">20</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;pilex.<span style="color: #660066;">add</span><span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">function</span> test<span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #003366; font-weight: bold;">var</span> now <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; setTimeout<span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;counter<span style="color: #339933;">++;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>counter <span style="color: #339933;">+</span><span style="color: #3366CC;">&quot; Hello world&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 5000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp;<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
pilex.<span style="color: #660066;">run</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Done &quot;</span><span style="color: #339933;">+</span>counter<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 5<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>
<pre><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">
</span></pre>
<pre><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">
</span></pre>
<h2>3.3 Pooling and reusing expensive, persistent resources</h2>
<p>I recommend using <a href="https://github.com/coopernurse/node-pool">node-pool</a>, since the management code is rather involved if you want to timeout/renew objects in the pool.</p>
<h2>3.4 Running arbitrary workflows when dependencies are matched</h2>
<p>If you can split your overall task into several independent async workflows, then <a href="https://github.com/creationix/conductor">Conductor </a>seems like a nice solution since it does dependency resolving for you.</p>
<h2>4. More good basic node.js patterns/snippets?</h2>
<p>Leave a comment, write a <a href="https://gist.github.com/">Gist</a>, write a blog post or send me a link to your repository + explain what it is and when/why it should be used. I want your code, will acknowledge your stuff and will keep periodically updating this page since I want to use it for my own reference/reminder. Thanks!</p>
<pre><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">
</span></pre>
<pre><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">
</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/02/02/essential-node-js-patterns-and-snippets/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Understanding the node.js event loop</title>
		<link>http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/</link>
		<comments>http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 22:48:47 +0000</pubDate>
		<dc:creator>Mikito Takada</dc:creator>
				<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.mixu.net/?p=1660</guid>
		<description><![CDATA[The first basic thesis of node.js is that I/O is expensive: ﻿ So the largest waste with current programming technologies comes from waiting for I/O to complete. There are several ways in which one can deal with the performance impact (from Sam Rushing): synchronous: you handle one request at a time, each in turn. pros: [...]]]></description>
			<content:encoded><![CDATA[<p>The first basic thesis of node.js is that I/O is expensive:</p>
<p>﻿<a href="http://blog.mixu.net/files/2011/01/io-cost.png"><img class="alignnone size-full wp-image-1661" title="io-cost" src="http://blog.mixu.net/files/2011/01/io-cost.png" alt="" width="509" height="362" /></a></p>
<p>So the largest waste with current programming technologies comes from waiting for I/O to complete.  There are several ways in which one can deal with the performance impact (from <a href="http://www.nightmare.com/medusa/async_sockets.html">Sam Rushing</a>):</p>
<ul>
<li><strong>synchronous</strong>: you handle one request at a time, each in turn. <em>pros</em>: simple <em>cons</em>: any one request can hold up all the other requests</li>
<li><strong>fork a new process</strong>: you start a new process to handle each request. <em>pros</em>: easy <em>cons</em>: does not scale well, hundreds of connections means hundreds of processes. fork() is the Unix programmer&#8217;s hammer. Because it&#8217;s available, every problem looks like a nail. It&#8217;s usually overkill</li>
<li><strong>threads</strong>: start a new thread to handle each request. <em>pros</em>: easy, and kinder to the kernel than using fork, since threads usually have much less overhead <em>cons</em>: your machine may not have threads, and threaded programming can get very complicated very fast, with worries about controlling access to shared resources.</li>
</ul>
<p>The second basis thesis is that thread-per-connection is memory-expensive:  [e.g. that graph everyone showns about Apache sucking up memory compared to Nginx]</p>
<p>Apache is multithreaded: it spawns a <a href="http://httpd.apache.org/docs/2.0/mod/worker.html">thread per request</a> (or <a href="http://httpd.apache.org/docs/2.0/mod/prefork.html">process</a>, it depends on the conf). You can see how that overhead eats up memory as the number of concurrent connections increases and more threads are needed to serve multiple simulataneous clients.  Nginx and Node.js are not multithreaded, because threads and processes carry a heavy memory cost. They are single-threaded, but event-based. This eliminates the overhead created by thousands of threads/processes by handling many connections in a single thread.</p>
<h2><strong>Node.js keeps a single thread for your code&#8230;</strong></h2>
<p>It really is a single thread running: you can&#8217;t do any parallel code execution; doing a &#8220;sleep&#8221; for example will block the server for one second:</p>
<div id="wpshdo_31" class="wp-synhighlighter-outer"><div id="wpshdt_31" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_31"></a><a id="wpshat_31" class="wp-synhighlighter-title" href="#codesyntax_31"  onClick="javascript:wpsh_toggleBlock(31)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_31" onClick="javascript:wpsh_code(31)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_31" onClick="javascript:wpsh_print(31)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_31" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> now <span style="color: #339933;">+</span> <span style="color: #CC0000;">1000</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp;<span style="color: #006600; font-style: italic;">// do nothing</span><br />
<span style="color: #009900;">&#125;</span></div></div></div>
<p>So while that code is running, node.js will not respond to any other requests from clients, since it only has one thread for executing your code. Or if you would have some CPU -intensive code, say, for resizing images, that would still block all other requests.</p>
<h2><strong>&#8230;however, everything runs in parallel <span style="text-decoration: underline;">except your code</span></strong></h2>
<p>There is no way of making code run in parallel within a single request. However, all I/O is evented and asynchronous, so the following won&#8217;t block the server:  <div id="wpshdo_32" class="wp-synhighlighter-outer"><div id="wpshdt_32" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_32"></a><a id="wpshat_32" class="wp-synhighlighter-title" href="#codesyntax_32"  onClick="javascript:wpsh_toggleBlock(32)" title="Click to show/hide code block">Source code</a></td><td align="right"><a href="#codesyntax_32" onClick="javascript:wpsh_code(32)" title="Show code only"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_32" onClick="javascript:wpsh_print(32)" title="Print code"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://blog.mixu.net/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_32" class="wp-synhighlighter-inner" style="display: block;"><div class="javascript" style="font-family:monospace;">c.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><br />
&nbsp; &nbsp;<span style="color: #3366CC;">'SELECT SLEEP(20);'</span><span style="color: #339933;">,</span><br />
&nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>err<span style="color: #339933;">,</span> results<span style="color: #339933;">,</span> fields<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">throw</span> err<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp;res.<span style="color: #660066;">writeHead</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">200</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'Content-Type'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'text/html'</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp;res.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'&lt;html&gt;&lt;head&gt;&lt;title&gt;Hello&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Return from async DB query&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp;c.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div></div>  If you do that in one request, other requests can be processed just fine while the database is running it&#8217;s sleep.</p>
<h2>Why is this good? When do we go from sync to async/parallel execution?</h2>
<p>Having synchronous execution is good, because it simplifies writing code (compared to threads, where concurrency issues have a tendency to result in WTFs).</p>
<p>In node.js, you aren&#8217;t supposed to worry about what happens in the backend: just use callbacks when you are doing I/O; and you are guaranteed that your code is never interrupted and that doing I/O will not block other requests without having to incur the costs of thread/process per request (e.g. memory overhead in Apache).</p>
<p>Having asynchronous I/O is good, because I/O is more expensive than most code and we should be doing something better than just waiting for I/O.</p>
<p><a href="http://blog.mixu.net/files/2011/01/bucket_3.gif"><img class="alignnone size-full wp-image-1663" title="bucket_3" src="http://blog.mixu.net/files/2011/01/bucket_3.gif" alt="" width="378" height="226" /></a></p>
<p>An event loop is &#8220;an entity that handles and processes external events and converts them into callback invocations&#8221;. So I/O calls are the points at which Node.js can switch from one request to another. At an I/O call, your code saves the callback and returns control to the node.js runtime environment. The callback will be called later when the data actually is available.</p>
<p>Of course, on the backend, there are <a href="http://stackoverflow.com/questions/3629784/how-is-node-js-inherently-faster-when-it-still-relies-on-threads-internally">threads and processes for DB access and process execution</a>. However, these are not explicitly exposed to your code, so you can&#8217;t worry about them other than by knowing that I/O interactions e.g. with the database, or with other processes will be asynchronous from the perspective of each request since the results from those threads are returned via the event loop to your code. Compared to the Apache model, there are a lot less threads and thread overhead, since threads aren&#8217;t needed for each connection; just when you absolutely positively must have something else running in parallel and even then the management is handled by Node.js.</p>
<p>Other than I/O calls, Node.js expects that all requests return quickly; e.g. <a href="http://stackoverflow.com/questions/3491811/node-js-and-cpu-intensive-requests">CPU-intensive work should be split off to another process</a> with which you can interact as with events, or by using an abstraction like <a href="http://blog.std.in/2010/07/08/nodejs-webworker-design/">WebWorkers</a>. This (obviously) means that you can&#8217;t parallelize your code without another thread in the background with which you interact via events. Basically, all objects which emit events (e.g. are instances of EventEmitter) support asynchronous evented interaction and you can interact with blocking code in this manner e.g. using files, sockets or child processes all of which are EventEmitters in Node.js. <a href="http://developer.yahoo.com/blogs/ydn/posts/2010/07/multicore_http_server_with_nodejs/">Multicore can be done</a> using this approach; see also: node-http-proxy.</p>
<p><strong>Internal implementation</strong></p>
<p><a href="https://github.com/ry/node/tree/master/deps">Internally</a>, node.js relies on <a href="http://software.schmorp.de/pkg/libev.html">libev</a> to provide the event loop, which is supplemented by <a href="http://software.schmorp.de/pkg/libeio.html">libeio</a> which uses pooled threads to provide asynchronous I/O. To learn even more,  have a look at the <a href="http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod">libev documentation</a>.</p>
<h2>So how do we do async in Node.js?</h2>
<p>Tim Caswell describes the patterns in his <a href="http://creationix.com/jsconf.pdf">excellent presentation</a>:</p>
<ul>
<li>First-class functions. E.g. we pass around functions as data, shuffle them around and execute them when needed.</li>
<li>Function composition. Also known as having anonymous functions or closures that are executed after something happens in the evented I/O.</li>
<li>Callback counters. For evented callbacks, you cannot guarantee that I/O events are generated in any particular order. So if you need multiple queries to complete, usually you just keep count of any parallel I/O operations, and check that all the necessary operations have completed when you absolutely must wait for the result; e.g <a href="http://stackoverflow.com/questions/4631774/coordinating-parallel-execution-in-node-js">by counting the number of returned DB queries</a> in the event callback and only going further when you have all the data. The queries will run in parallel provided that the I/O library supports this (e.g. via connection pooling).</li>
<li>Event loops. As mentioned earlier, you can wrap blocking code into an evented abstraction e.g. by running a child process and returning data as it it is processed.</li>
</ul>
<p>It really is that simple!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
	</channel>
</rss>

