Search Logger
Posts from: Tom Hughes-Croucher

Author Archive

Happy First Birthday, JSMag

10:27 pm - March 3, 2010 in Yahoo! User Interface Blog

Tom Hughes-Croucher is an evangelist for the Yahoo! Developer Network.

Our friends over at JSMag are celebrating their first birthday. If you haven’t read JSMag it’s a monthly PDF magazine that covers news on hot JavaScript topics and provides practical tutorials.

JSMag are giving away a free issue from their first year. Simply log into your JSMag account and use the code ‘oneyear’ to get a free issue.

When selecting your free issue, you may want to seek out the articles in JSMag written by Yahoos frontend engineers or about YUI over the last 12 months:

  • March 2009
    • Matt Henry on unit testing with YUI
  • April 2009
    • Yours truly on Profiling your JavaScript
  • June 2009
    • Yours truly on Build Scripts
  • July 2009
    • Stoyan Stefanov on Function Patterns
  • August 2009
    • Jon LeBlanc on YQL and browser MVC
  • August 2009
    • Stoyan Stefanov on function patterns
  • September 2009
    • Chistian Tiberg on using administration system with YUI
    • Stoyan Stefanov on more function patterns
  • October 2009
    • Chistian Tiberg on inline editing with YUI
    • Stoyan Stefanov on more constructor patterns
  • November 2009
    • Yours truly on Enhancing YQL with server-side JavaScript
    • Stoyan Stefanov on more inheritance patterns
  • December 2009
    • Christian Tiberg on using the YUI2 datatable and chart
      components
    • Stoyan Stefanov on more reuse patterns
  • January 2010
    • Christian Tiberg on using YUI to build desktop gadgets for Windows
    • Stoyan Stefanov on the sandbox pattern
  • February 2010
    • Stoyan Stefanov on the private members pattern
  • March 2010
    • Yours truly with an overview of server-side JavaScript
    • Stoyan Stefanov on currying

Happy Birthday, JSMag!

 

Upcoming Industry Conferences

12:24 am - March 30, 2010 in Yahoo! User Interface Blog

We love great tech conferences, and we know that a lot of you having amazing things to share. So I’ve put together this list of conferences and barcamps coming up that are looking for speakers or participation.

We are going to be at some of these and we hope we’ll see many of you there speaking or not.

Professional Conferences

Web 2.0 Expo NYC 2010

Submission Deadline: April 12th, 2010
Web 2.0 Expo NYC Submission Page
Conference Date: 18th – 21nd October 2010
Location: New York, NYC, USA

EuroPython 2010

Submission Deadline: April 30th, 2010
EuroPython Submission Page
Conference Date: 19th – 22nd June 2010
Location: Birmingham Conservatoire, Birmingham, UK

Barcamps

We’ll keep updating you on event speaking deadlines as they come up. Let me know what I missed in the comments section and we’ll make sure your event is included here.

 

Part 1: Understanding event loops and writing great code for Node.js

7:29 pm - October 4, 2010 in YDN Blog

As usual JSConf.eu was one of the best conferences I've been to this year. It's always a delight to hang out with some of the smartest JavaScript coders on the planet, and doing it in the very trendy city of Berlin was a nice bonus. There are a few great recaps of JSConf so I'm not going to focus on those; instead I'm going to expand the talk I gave.

Programming inside an event loop is something most programmers only have a passing familiarity with. Node.js is quickly gaining traction as a very popular event loop-based server for JavaScript. It gives people the ability to write JavaScript on the server, which has access to things like the HTTP stack, TCP, file I/O, and databases. However the kind of programs that we write in this context tend to be very different from the kind of programs we write for browser-side applications or sites.NodeJS events

In the browser, the bulk of the program tends to be involved with setting up the user-interface, and then there are some small event callbacks that are enacted — most typically, based on user interaction with the browser. For example, when the user clicks Submit on a form, we intercept the click and validate their submission.

There is an important point here: in most browser programming, programmers are only dealing with events caused by the user, and the user can only do so many things at once. Moreover the callbacks for those events tend to be very discrete and don't cause other events. Some libraries, such as YUI, have custom event support. But it is often thought of an advanced feature.

On the server, however, there isn't a user to drive a variety of interactions. Instead we have a whole range of reactions to take on many different kinds of events. Node.js takes the approach that all I/O activities should be non-blocking (for reasons we'll explain more later). This means that all HTTP requests, database queries, file I/O, and so on, do not halt execution until they return. Instead they run independently and then emit an event when the data is available.

This means that programming in Node.js has lots of callbacks dealing with all kinds of I/O and then initiating other callbacks for other kinds of I/O. This is a very different from browser programming. There is still a certain amount of liner setup, but the bulk of the code involves dealing with callbacks.

Because of these different programming styles, we need to look for patterns to help us effectively program on the server. That starts with the event loop, so let's take a look at that in more depth.

I think that most people intuitively get event-driven programming because it's like everyday life. Imagine you are cooking. You are chopping a bell pepper and a pot starts to boil over. You finish the slice you are doing, and then turn down the stove. In daily life, we are used to having all sorts of internal callbacks for dealing with events, and yet, like JavaScript, we only do one thing at once.

Yes, yes, I can see you are rubbing your tummy and patting your head at the same time, well done. But, if you try to do any serious activities at the same time, it goes wrong pretty quick. This is like JavaScript. It's great at letting events drive the action, but it is "single-threaded" so only one thing happens at once.

Another way to think about this event loop is a post (or mail) man. To our event-loop postman, each letter is an event. He has a stack of events to deliver in order. For each letter (event) the postman gets, he walks to the route to deliver the letter. The route is the callback function assigned to that event (sometimes more than one). However, critically, since our mailman only has a single set of legs, he can only walk a single code path at once.

Sometimes, while the postman is walking a code route someone will give him another letter. This is because the callback function he is code walking has emitted an event. In this case the postman delivers the new message immediately (after all someone gave to him directly instead of going via the post office so it must be urgent). The postman will diverge from his current code path and walk to the code path to deliver the new event. He then carries on walking the original event that emitted the event he just walked.

Let's look at another example. Let's give the postman a letter to deliver that requires a gate to be open. He gets there and the gate is closed, so he simply waits and tries again, and again. He's trapped in an endless loop waiting for the gate to open. But if there is a letter on the stack that will ask someone to open the gate so the postman can get through, surely that will solve things, right?

Unfortunately it won't, because the postman will never get to deliver the letter because he's stuck waiting endlessly for the gate to open. This is because the event that opens the gate is external from the current event callback. If we emit the event from within a callback, we already know our postman will go and deliver that letter before carrying on. However, when events are emitted external to the currently executing piece of code, they will not be called until that piece of code has been fully evaluated to its conclusion.

We can use this to write a piece of code that creates a loop that Node.js (or a browser) will never break out of:

EE = require('events').EventEmitter;
ee = new EE();

die = false;

ee.on('die', function() {
    die = true;
});

setTimeout(function() {
    ee.emit('die');
}, 100);

while(!die) {
}

console.log('done');

In this example, console.log will never be called because the while loop stops Node from ever getting chance to callback the timeout and emit the 'die' event.

This is a really important piece of information, because while it's unlikely we'd program a loop like this that relies on an external condition to exit, it clearly illustrates how Node.js can only do one thing at once. And getting a fly in the ointment can really screw up the whole server.

Let's look at the standard Node.js code for creating an HTTP server:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/'

This code is the 101 example from the Node.js web site. It creates an HTTP server using a factory method in the http library. The factory method creates a new HTTP server and attaches a callback to the 'request' event. The callback is specified as the argument to the createServer.

What's interesting here is what happens when this code is run. The first thing Node.js does is run the preceding code from top to bottom. This can be considered the 'setup' phase of Node programming. Since we attached some event listeners, Node.js doesn't exit, but waits for an event to be fired. If we didn't attach any events, then Node.js would exit as soon as it had run the code.

So what happens when we get an HTTP request? When an HTTP request is sent to the server, Node.js emits the 'request' event that causes the callbacks attached to that event to be run in order. In this case there is only one callback, the anonymous function we passed as an argument to createServer. Let's assume it's the first request the server has had since it setup. Since there is no other code running, the 'request' event is emitted and the callback is just run. It's a very simple callback and it runs pretty fast.

Let's assume that our site gets really popular and we get lots of requests. If, for the sake of argument, our callback takes 1 second, then if we received 2 requests at the same time, they can't both be run at once, and the second request isn't going to be acted on for another second or so. Obviously, a second is a really long time, but as we start to look at real-world applications, the problem of blocking the event loop becomes more dangerous as we can see the damage it could have on users.

The upshot of this is that we want to keep Node.js as event-driven and non-blocking as possible. In the same way that an I/O event that can be slow should use callbacks to indicate the presence of data Node.js can act on, the Node.js program itself shouldn't be written in such a way that any single callback ties up the event loop for extended pieces of time.

The operating system kernel actually handles the TCP connections to clients for the HTTP server, so there isn't a risk of not accepting new connections. But there is a real danger of not acting on them.

This means that we should employ two strategies for writing Node.js servers:

  • Once set up has been completed, make all actions event driven
  • If Node.js is required to process something that will take a long time, consider delegating with web workers

Taking the event-driven approach works effectively with the event loop — I guess the name is hint it would — but it's also important to write event-driven code in a way that is easy to read and understand.

In the previous example, we used an anonymous function as the event callback. This makes things hard in a couple of ways. Firstly, we have no control over where the code lives; the anonymous function must live where it is attached to the event either via a factory method or the on method of an EventEmitter. The second issue is debugging: if everything is an anonymous event, it can sometimes be hard to distinguish similiar callbacks from each other when an exception occurs.

In part 2, we'll discuss how to write good event-driven code based on patterns that support our use of the event loop. If you can't wait until then, you can take a look at the slides from JSConf.eu:

 

Announcing a Node.js Book Project

1:46 pm - November 9, 2010 in YDN Blog

I hope you've all been following along with all the great stuff that's been happening at YUIConf this year.

As part of the conference proceedings, I'm excited to announce a preview release of my upcoming book for Yahoo! Press in association with O'Reilly Media. Up and Running With Node.js is a guide to Node.js aimed at giving you the combination of the background knowledge you need to use Node well, and the hands-on tutorials you need to get started fast.

While this initial release isn't a huge one, as we progress through the process of writing we are going to be periodically sharing drafts of the book with the community. We'd love to get your thoughts and feedback on what we are doing. I've based much of what I've written on the many Node talks I've given at conferences world-wide. I hope we can write the book that you need to make the most of the amazing platform Node.js offers, so all feedback is helpful.

You can download the Node Book Preview as a PDF. I look forward to hearing from you.

— Tom

 

Hacking the Kinect, Games in Python, and Fighting Firesheep with HTTPS

2:07 pm - November 18, 2010 in YDN Blog

Time for another set of awesome links on a Thursday.

 

Smoked Turkey, killer editing with VLM, and NoSQL

4:16 pm - November 25, 2010 in YDN Blog

Happy Thanksgiving! A nerdy set of links for those of you enjoying in the US and everywhere else. — Tom

  • I revisited Peteris Krummin's VLM plugins you should know about in my quest to 'grow up' from Textmate.
  • I've also been reading some great thoughts from Basho on how to architect document (nosql) databases with specific examples in Riak.
  • Rob from Mozilla expanded on the dangers of dead code elimination which lead to last week's suspect results for IE9 and Sunspider.
  • I've been keeping an eye on arewefastyet.com in anticipation of the new JavaScript engine in Firefox 4 overtaking Google's V8 engine from Chrome for performance. In wars over performance everyone wins.
  • Here in America, it's Thanksgiving today. While I'm not American (and I'm vegetarian), I have to admit that CloudKick's turkey smoking alerts are just really cool. If the temperature varies on their smoker, they get a text to let them know.
 

Google Chrome, Minecraft CPUs, and Web Socket doom!

2:45 pm - December 9, 2010 in YDN Blog

It's been a pretty busy week in web tech! So here is some of the stuff happening this week and some good stuff that you might not have seen already.

 
 
 
 
 
 
It's All About Search | © clsc.net |
2012.05.1823:30
Tech used here: Valid HTML - Valid CSS - Valid RSS - JavaScript - PHP - Smarty - MySQL - and a partridge in a pear tree.