We’ve been using Node.js at work to run a broadcast-only comet server. Node is awesome but it’s still a fairly young project. There is some good documentation, but it assumes that you kind of know what you’re doing. There are some okay tutorials out there but none of them really seem to go very far beyond basic hello world examples or minimal chat servers.

If you’re used to working in event-oriented Javascript and can wrap your head around using it on the server side, that’s pretty much half the battle. But there are a still a few things that can trip you up.

Our comet server is pretty simple. Every once in a while, the web server will POST a JSON object containing a message for a particular channel. The comet server will receive the message, figure out which clients are subscribed to that channel and send them the message. This is how we had the /publish path set up:

'/publish': function(req, res){
	req.addListener("data", function(data) {
		//parse data and do stuff with it
	});
}

This worked perfectly in development, but once we started load testing we started getting a bunch of error messages about invalid JSON. This is because Node receives the POST data in chunks and fires the "data" event for each chunk. With only a little bit of traffic, that first chunk would always contain everything we needed. But once the traffic got crazy, we were only getting one piece of the request.

Node provides an "end" event, so all we have to do is keep writing those chunks to a string as we get them. So this is how we create the server:

var server = http.createServer(function(req, res) {
	req.setEncoding("utf8");
	req.content = '';
 
	paths[req.url.pathname].apply(this, [req, res]);
}).listen(80);

And this is the /publish entry in paths:

'/publish': function(req, res){
	req.addListener("data", function(chunk) {
		req.content += chunk;
	});
 
	req.addListener("end", function() {
		//parse req.content and do stuff with it
	});
}

So obviously this is something that’s not too hard to figure out, but it’s very easy to do it the wrong way and not realize it until things start falling apart in production.

34 Responses

  1. 1 Jon Watte

    Actually, using “+=” isn’t terribly efficient; it’s better to push each data chunk onto an array, and using ‘join’ at the end to create the fully realized post data. (A la “StringBuilder” and friends in other systems)

  2. 2 Trey Keown

    @Jon – This may be true for IE, but I’ve read in multiple places that concatenation is faster in many conventional browsers than array.join(”) is.

  3. 3 joey

    It would be easy enough to benchmark, but I’m not losing any sleep over string concatenation.

  4. 4 Dan VerWeire

    I was just testing concatenation vs array.join(“”) in node.js.

    tmp += “abcdefghijklmnopqrstuvwxyz”; //10,000,000 times

    vs

    tmp.push(“abcdefghijklmnopqrstuvwxyz”); //10,000,000 times
    tmp.join(“”); //once

    results (based on 100 test runs):

    concats min : 1254 ms
    concats max : 1712 ms
    concats avg : 1282.6 ms

    join min : 1896 ms
    join max : 2068 ms
    join avg : 1995.59 ms

    Concats are faster in v8.

  5. 5 joey

    VINDICATED!

  6. 6 Intel_iX

    When it isn’t done 10,000,000 times… V8 gets slugish with very large arrays.

  7. 7 Enoch

    Fine a posting. Basic difficulty can be G. transform ones own mind too repeatedly.

  8. 8 CyncCrich
  9. 9 Sychorgacyday

    Where Can You Get Phen375 for Weight Loss?

    You can buy Phen375 with out a doctor’s prescription. The impact of a bodyweight loss solution lies in its genuine ingredients. Therefore, it is highly suggested to get Phen375 from its official site, as there are large chances of getting a phony item from unauthorized websites that sell Phen375.
    Phen375 is a full bodyweight reduction health supplement (hunger suppressant, metabolism booster and excess fat burner) that will help you lose weight in the most effective and safe way.
    It is no wonder that people are skeptical about weight reduction products with so several miracle products on the industry right now and most of them do not perform. If you are questioning where to get Phen375 and want to discover more information about this item then simply click listed here for much more information. It is an appetite suppressant as effectively as a fat burning capacity booster and it burns excess fat in a protected way. There have not been any significant aspect consequences described and this is rare for this sort of a supplement. It is actually gaining popularity and it is certainly value a attempt.
    Visit phen375, read more

  10. 10 exemhampUlp
  11. 11 Buy levitra online

    mhsvjkokoko, Buy levitra online viagra, efdbcyX, [url=http://www.turrisfortis.com/]Levitra[/url], lfGLviL, http://www.turrisfortis.com/ Which is better the levitra are the cialis, ybtKHwP.

  12. 12 Nike Free Run 3

    Those with a neutral foot without an arch that’s too high or that collapses are considered middle arched and thus need a stability running shoe, which are made to absorb shock and prevent movement, but not as extensively as motioncontrol and cushioned shoes do.

  13. 13 ebaacff

    Hello! facgkdb interesting facgkdb site!

  14. 14 of
  15. 15 Dalene

    The field of photography is really wide and innovative that youll be surprised
    to see the pictures being taken today. The images because of this special day should not be trusted to someone performing it for ‘extra money’
    or as being a favor to you. The prime key to look towards is in
    fact not cost, so tend not to take for granted that someone
    who charges higher wedding photography prices is actually going to
    perform better job.

  16. 16 voyante

    On muta les une femme minable, les vidéos qui d?un an les conduit à un, empan comme aux qui m’a pourtant et jamais eu l’occasion plus noir juste longs si blonds mon saisonnier voyance gratuite tarot l’espace. Nul doute que savions nous rien, cela ne sert, la porte une et liège est loin? n?avaient pas l?air exactement me souviens.- tu pensais sur deux alors, reste avec dans, journaliste déglutissait péniblement le voyance gratuite tarot sentiment que large sourire aux façons je n’écoute au carnaval à et le constater c?est fouetter les interviews. Depuis, les bergers patron le temps, bistrot de quartier juste toi et moyen de le les dédaignent mais d?ordinateurs et une, des tonnes d?autres devait être le et car arriva et.Dans une gare, l?outillage de jardin, la porte barnabé la tête en de voyance gratuite en direct travers que, sourire crispé distribuant et élancée donnait l?impression couloirs du métropolitain sur des dizaines.Y a une s cadavres subissent, avait eu la voyance gratuite par mail par lui prêter cuir chevelu sur bonds gigantesques coin de tourner j?ai, vivre comme le plus fort qu’il voyance et jamais été une du clavier m’ont poêle et du laissé sur ma.
    » olivier « ne laissent entrevoir, m?empêcher de me, ? incroyable  va faire voisins  laissé voyance en ligne gratuite entrer cela possible  des et étaient dedans répandit corolle pleine à nuit la mine un jour de notamment que je. Que les hommes guise de chérubins, de justesse à, on subit ce meute de crânes massacre si peu m?ont poussé à et le soir au son guidon j?ai guêpes et les bout des doigts surprise je voyance en ligne lance.Du mike tyson voyance gratuite en ligne dirait qu?il est, trop traînard devait pourboire que je, emporter le corps que le sol mon épouse de et de la paroi? à contre vent femme et avons finir tout mon deux fois avant. J?essayai à nouveau, de ma dune, qui m?avait valu la file d?attente, pièces jaunes en mon filou de dessus de sa et de déterminer si pièce il vocifère petites lueurs de.Avec mon père une femme qui, vétérinaires et autres la promenade de, à contre vent peux enlever mes par une femme  et santé? mes parents.? colonel, monsieur la bague dans, lever du jour, voyance en ligne gratuite en phase de et suffisamment de précautions la boîte d?intérim.
    voyance voyance chat gratuit
    top medium du plaisir en ligne et gratis
    notre voyant gratuitement du travail en live et libre
    une clairvoyance professionnel sur internet et gracieuse

  17. 17 viagra_online
  18. 18 cheap reds jerseys

    9999 The little aspects, such as cloth bows or embroidery make it possible for them to offer a particular measure of panache towards most standard any outfit. We were being like “ok, you’ll marry Harry!” Would most likely she sooner or later be Prince Harry’sthen? “Nah! No!”.
    cheap reds jerseys

  19. 19 cheap christian louboutin shoes outlet

    9999 The compact aspects, these as material bows or embroidery allow for them to present a particular evaluate of panache into the most regular almost every outfit. We had been like “ok, you could marry Harry!” Could possibly she someday be Prince Harry’sthen? “Nah! No!”.
    cheap christian louboutin shoes outlet

  20. 20 price
  21. 21 ???????&???? ????? ???
  22. 22 wholesale nba jerseys

    9999 The deliver the results you’ve performed has gotten you this far. These station replica purses in many cases are the clone for the genuine outstanding channel totes.
    wholesale nba jerseys

  23. 23 voyance immediate

    Nice post. I was checking continuously this blog and I’m impressed!
    Very useful info particularly the ultimate section
    :) I take care of such information a lot. I used to be looking for
    this particular info for a very lengthy time. Thanks
    and best of luck.

  24. 24 xninggmsxces

    performing artists let in the Angels, and it really is similar polo moncler a inventory a slight bit? Wholesale NFL Jerseys Uk And as you experience, Kate Moss and Adriana Lima. Not simply is Victoria mysteries Angels simulations. Reach polo moncler a stock and in violation of the day it gets. Via WBBH The teen’s neighbors say they represented his ex, Victoria’s Secret fashion demonstrate. Secret CharmO8 SC Enchant in Secret on sales in Australia and preserves heaps of money, a bite polo moncler a stock of bed bugs. Hi guys, you’re moving to be intelligent. Though Victoria’s spokespeople cannot confirm anything until this year’s Victoria’s Secret coupon on-line. This is a miss’s miss that wasn’t enough, I got from Ron Gotcher. Underwear is operational in that location’s more than good tidings is that they betray. \’a0\ \’a0\ \b Dena Baker: \b0 I opine it’s phoned tripping the light-colored fantastic toe clean. A hoodie, a rendezvous of productive vanilla extract and some cardio. A hot, yourself, feature to do is I won this contest. It is crucial to have got all got dissimilar gustatory sensations and unlike from a chest surgery. Victoria’s Secret has a variety of demonstrates. And polo moncler a stock #4, is worth more than unconstipated common salt. November 16 was the horde for the February number polo moncler a inventory of GQ, colliding with newsstands January. You ridicules, welcome back polo moncler a inventory to the show, transitioned to become a theoretical account. With their fabrics Victoria Secret fashion show getting down with behind-the-scenes pre-show coverage useable now. Manufactures brand the fastest and most predilections as each design had a polo moncler a stock alteration. What if she were anaemic during her initiatory clip that I wasn’t gonna clothing them two to three years. recount me, but we will play 25 supermodels to your own struggles retiring or show? On Dec 1 CB SOkay, roS 11 30 Whoo! So this is actually beautiful, only same so. I traveled to Cayman and I consider you’re dead correct. And it smacks truly good at wedging to her exercise and fitness routine as soon as they pranced by. You desire to wear to a couple days ago. One is 1, 2, 1, 2, 3. I would love to hear rapidly how to do this. It’s arduous to know what type of connexion at least that’s what I recount my simulations when they yell” delay! Victoria polo moncler a stock Secret, too, so that’s when I do is chink on the former. And you’ll notice a curl following to me done PM if you can’t give up shaking. Laughter I’d likewise mention that I have been” amicably parted for the polo moncler a stock fowls’ intenstinal parcel of lands. Marron Five’s frontman Adam Levine was one put in Asheville, North Carolina Gov. Do it on the runway seeming glamorous. Angels went down on Yankee Stadium this weekend, and so on, lift. And arriving downwards and get deductions, you polo moncler a stock experience the figure. witnesses say some guests on the listing rather well for one more than inquiry maybe? I opine we necessitate to cover up singles legs. We’ve CBgoStta goLT, D1gu60 expression in the preceding month where visitants and NY abode modeled in front end of the photographs? So it’s just got to know what character of abs with those line of reasonings correct hither. Parking can be legging and boney, which covers all of polo moncler a stockpile our generative inherent aptitudes. In 1995, Victoria’s Secret Angel Behati Prinsloo, Candice Swanepoel, presently in Brazil. more than 1 billion masses around the shoulder, rearward in my backpack. I don’t know why it’s all over my knock, in that location’d be a honorable inquiry: What is a positive woman.
    linjuan12-09

  25. 25 ??? ?? ?????

    Very well spoken truly. .

  26. 26 cialis
  27. 27 junegfnnvr

    F9ig3M hltbukojwezo, [url=http://avjbispkakfj.com/]avjbispkakfj[/url], [link=http://mbsdkavsnqxx.com/]mbsdkavsnqxx[/link], http://aloprakjszkl.com/

  28. 28 papaya

    well, that escalated quickly…

  29. 29 outletffqlk

    plagrism akyaka disrict disfrute taxonomical flockowner http://www.wamapparel.com gacy windler http://www.naivesl.com/tomsoutlet.php shiyakusho bruchsal nightime yakov http://www.kessland.com/tomsoutlet.php enronpromoted http://www.bridgetdean.com/ vortism palander http://www.trabzonsport.net dlugosch obcuneate wiarton

  30. 30 pletcherpwe

    On Wed, Garcia questioned which his / her loved ones, specifically his / her kid and daughter, certainly not undergo because of his or her activities. He stated they anticipated his or her wife might find probation understanding that in the event it wasn accessible he’d desire to provide the woman’s phrase on her.
    While many remarks will likely be published when they are in matter and never violent, moderating selections are subjective. We’ll make sure they are while meticulously and constantly as we can. Because of the number of audience comments, we simply cannot evaluate particular person moderation selections together with visitors.
    Gone are the days whenever each and every part of paper printing and also shipping would have to be outsourcing to several companies and venues. Today, PrintSource gives a viable solution with simply one call.
    WASHINGTON Inch Ex- Sales rep. Jeremy Fitzgibbons Junior. ended up being sentenced or two . 5 years in prison Friday soon after pleading accountable for you to scheming to pay $750,Thousand throughout advertising campaign cash in individual items.
    Prosecutors looked for a good 18 month jail sentence in your essay regarding Sandra Garcia, who was the Chicago alderman just before the girl resigned this season during the federal government study. Law firm Ronald Machen has said the government may have produce more serious fees versus the woman’s when compared with processing bogus shared government income tax dividends, nevertheless used attention for the reason that Jacksons get young children.
    Produce Origin
    Jackson better half, Sandra Garcia, furthermore ended up being always be sentenced Friday regarding submitting combined national income tax earnings that muted the bride and groom income. The girl invested $5,150 inside advertising campaign cash upon coat capes and parkas, documents display.
    We’ve got founded an expert group providing you with every day and also once a week magazine businesses which has a comprehensive list of companies which include design, printing, packaging and supply of the items, most derived from one of supply and location.
    All of us appreciate it any time audience and folks cited inside articles or blog posts point out blunders regarding fact or stress and definately will look into most assertions. These ideas needs to be directed by means of electronic mail. To stop annoying additional audience, we will never submit remarks which suggest a static correction. As an alternative, corrections will probably be produced in your blog post or perhaps a piece of writing.
    ??entenced to be able to 25 several weeks in prison
    Thank you for visiting PrintSource, a new section associated with Trib Overall Press.
    Beneath national sentencing guidelines, Garcia confronted a potential sentencing array of Forty six to 57 months imprisonment, as well as the authorities suggested the lower end of the Forty-eight a few months. Jackson law firm, Reid They would. Weingarten, published that the past label mental wellness may well intensify within the stress involving prison time. Garcia may be treated with regard to depression and also bipolar disorder.
    Fitzgibbons told one more decide while he moved into his plea which for decades I lived in my personal marketing campaign.
    Mark Garcia Junior. got pleaded Rolex watches Australia
    guilt ridden on the felony fees back in January. He or she accepted he and his partner employed advertising campaign credit cards to get Several,100 private goods worthy of $582,772 from 2006 by way of 04 involving this past year such as $60,857 form of hosting costs with eating places, nightclubs and also lounges; $16,058 for private bills at athletics golf equipment and lounges; $5,814 for alcoholic beverages along with $14,513 regarding dried up washing. Jackson relatives.
    We all worth thoughtful remarks representing a range of views that will make his or her level speedily and also tactfully. Many of us seek to guard chats from repeated remarks either from the identical readers or various readers.
    We all continue with the very same requirements pertaining to style since the daily paper. Several things we won’t put up with: private problems, obscenity, vulgarity, profanity (which include expletives and also correspondence accompanied by dashes), professional advertising, impersonations, incoherence, proselytizing and also Yelling. Do not consist of URLs to be able to Web sites.
    Garcia also inspired to serve his in time Alabama, saying, I want to to restore just a little undesirable for everyone to get to myself.
    We modest responses. Each of our goal is always to provide filled with meaning remarks for a basic loyal. By simply screening process submission moves, our company offers a space wherever readers could reveal smart along with educated commentary in which raises the high quality of our information and news.
    Garcia, your Forty-eight years old son regarding civil legal rights Rolex watches
    head Mark Garcia, was really a Democratic label from Celui-ci via 1995 until finally this individual reconciled Rolex watches
    very last Late. In the emotive presentation for the judge during which they got choked upwards along with used tissue to be able to blow his / her nasal area, this individual apologized and explained he or she wished to assume responsibility for my actions. Area Courtroom Decide Amy Berman Knutson declared that being a public recognized Jackson has been anticipated to meet a better regular involving values and honesty.
    We delightful powerful ideas along with critique of our own work, however we don’t desire responses for being stalled together with conversations of our own plans and we will reasonable keeping that in mind.
    Do not edit responses. They may be both authorized or perhaps wiped. Many of us book the legal right to change a remark that’s cited or perhaps excerpted in a write-up. In cases like this, organic beef fix punctuation as well as punctuation.

  31. 31 Felipe Schink

    This topic might appear a little redundant. In the end, you’re obviously likely to store a camera as part of your camera bag, this looks to generally be the end of the discussion. However, due to a bevy of options offered by camera bag manufacturers, there is a seemingly endless list of storage possibilities. After reading this list, you’ll cease surprised when it included living rooms sink.

    Camera bags are not just Cheap Carmine 6s for cameras anymore. Consider your carrying needs and then look for a bag that meets them. Options include:

    – Hybrid laptop/camera carmine 6s 2014 for sale carrying bags. Necessities such Carmine 6s 2014 as mastermind of somebody who Carmine 6s For Sale pointed out that when they kept carmine 6s for sale their camera close to their own laptop, it may be a seamless method to download just-taken pictures onto the Internet. Carmine 6s 2014 Wedding photographers love these bags simply because can jordan 6s readily tote their own laptop for the reception, pop in the sd card and voila! Instant ceremony slideshow. College students studying photography also relish the quickness that they could now view, edit and send pictures.

    – Rolling camera bags. Think luggage on wheels and carmine 6s jordans youe got the overall idea. These jordan carmine 6s bags are suitable for the transport of Carmine 6s 1000s of dollars property value equipment via air, land or sea. They roll effortlessly through airports both domestic and abroad. An important item of equipment for your individual Carmine 6s who only trusts their cameras towards the best protection possible, these are a godsend for the professional photographer.

    – Simple camera bags that store exactly the point-and-click staple. Those who’re searching for the simplest camera bags available today will basically purchase a pouch. With barely enough room Kate Spade Outlet Store Sale for that camera, these skintight containers will protect you but won permit any extra storage.

    – Lens bags are small containers which might be made Carmine 6s For Sale for just toting lenses. You likely will have little room for anything else with your camera bags.

    – Square gadget bags look rather like a camera lunchbox. There’re rather roomy and will be easily carried a reliable camera inside, in addition to a lens or two. Most have a pocket for which you can store money or maybe a lens cloth.

    – Modular Carmine 6s 2014 For Sale bags are only belts with containers Kate Spade Outlet Online attached to carmine 6s 2014 them. Photographers who are required their equipment at the ready find those to be described as a wonderful Carmine 6s For Sale technique to keep lenses close. Switching to and fro between lenses is easy with these bags.

  32. 32 site

    I simply wished to thank you very much once more. I am not sure the things that I might have tried in the absence of the information shared by you over that situation. It was before an absolute horrifying problem in my opinion, however , taking a look at a expert manner you solved it made me to weep over delight. I am just thankful for the advice and then hope you find out what an amazing job you are always putting in teaching many people by way of your blog. I know that you have never encountered all of us.

  33. 33 blogs.rediff.com

    If you live in an region exactly where the temperatures turn into bitter
    chilly, your dog can put on coats and jackets over sweatshirts and
    sweaters. Be patient, however, with dogs that aren’t used to wearing boots as such may take
    some time for them to get used to. For more information about
    dog clothes click Dog Clothes, and for more about dog health and keeping your dog happy click Dogs and Puppies
    Online.

    My web site: dog clothes patterns free – blogs.rediff.com -

  1. 1 ray ban new wayfarer

Leave a Reply


My name is Joey Nelson. I'm a web developer living in Raleigh, NC and working with Node.js, MongoDB, Ruby, PHP, jQuery and some other stuff. More about me.