Hacker News new | comments | show | ask | jobs | submit login
Koa – Next-generation web framework for Node.js (koajs.com)
281 points by m0hit on Dec 19, 2013 | hide | past | web | favorite | 121 comments



0s: "next generation web framework for node.js" (oh god, not another)

5s: "designed by the team behind Express" (wait what?)

6s: "Through leveraging generators Koa allows you to ditch callbacks" (wow, ok. oh hey, that makes "next generation" not just marketing fluff)

18s:

  app.use(function *(next){
    var start = new Date;
    yield next;
    var ms = new Date - start;
    this.set('X-Response-Time', ms + 'ms');
  });
(oh sweeet)


I found the GIF on this page explains it pretty good: https://github.com/koajs/koa/blob/master/docs/guide.md


pretty well


Reading this comment makes me sad. Does this mean you would have immediately closed the tab, irregardless of technology, if they didn't namedrop?


I was already giving it the benefit of the doubt by reading any further than "next generation web framework for node.js".


Couldn't agree more. Happy that I did though.


Too many things claim to be a "next generation framework", that it usually is a let down because it is just a rehash of something.

But this is something new that looks like it can be good. I've been wondering when it would be announced, as TJ has been working on it for a while: https://github.com/visionmedia?tab=activity


Offtopic: *irregardless is not a word, Just use regardless.


Like it or not, irregardless is here to stay. Languages change, mispellings become the correct way to spell things, words become their own antonyms, and a lot of other very strange things. Embrace it!


It's just wrong. Why embrace things that don't make sense? Are we embracing the Idiocracy?


I reject your implication. Just because a lot of people use it does not make it grammatically accurate.

http://en.wikipedia.org/wiki/Irregardless


> Just because a lot of people use it does not make it grammatically accurate.

Actually, that's exactly what it does... over time. Where exactly do you think our language, as it exists today, came from?



@swalkergibson flammable and inflammable both mean the same thing.



Of course language evolves, but a double-negative is a double-negative, no matter how you slice it. Do you have another example of a single word that is a double-negative?


And yet one of the father's of written modern English, Chaucer himself often used double negatives [0].

ex:

"Ther nas no man no wher so vertuous" ("There never was no man nowhere so virtuous")

"He nevere yet no vileynye ne sayde / In all his lyf unto no maner wight" ("He never yet no vileness didn't say / In all his life to no manner of man").

The modern English language (written and spoken) has been in constant flux for the last 600+ years. What was once required is now antiquated, and what was once verboten is now required.

At this moment in time, double negatives are frowned upon. However, that may change in the future, and it's possible that irregardless is the start of a new set of changes in the language.

[0] - http://en.wikipedia.org/wiki/Double_negative


> And yet one of the father's of written modern English, Chaucer himself often used double negatives [0].

It's worth noting that neither of your examples has a double negative. Triple negative (the second possibly quadruple), sure, but not double.

> At this moment in time, double negatives are frowned upon.

I don't know that there's really a shift in time with the double negative, its a stylistic rule, and, much like the Pirate Code, stylistic rules in English are more what you'd call guidelines than actual rules.

Or, looked at another way, more like training wheels.


Guidelines indeed. For reference, here is an example of a double negative from the Prologue to the Canterbury Tales:

Nowher so bisy a man as he ther nas [0] (Nowhere so busy a man as he there none)

[0] http://www.bartleby.com/40/0102.html line 321


Unless?


Oh snap.


Welcome to Hacker News, home of the worlds largest contrarian user base.


That link, and the mere fact it exists, contradicts your point. Irregardless is a word [...]

Irregardless, it's not about being grammatically correct, but being socially accepted and understood; just like slang and broken grammar that develops in subcultures, it ain't no goin anywhere!


So why would you want to use it? What is the point of saying irregardless vis-a-vis irrespective or regardless?


Trolling the language police is a pretty good reason, actually.


I am whelmed by this whole conversation!


Is it fair to call this willful ignorance?


it's because of the hyperbole:

> next generation web framework for node.js

I don't think they need that, just list the stand-out features first. And yes, referring to past accomplishments does give it more credibility.


This utilizes generators heavily. Generators are within the ES6 spec, which is the next generation of JavaScript.

This might be one of the very few instances that "next generation" is a valid statement.


You don't believe in social proof and a history of success?


I would.


Saw something similar in Martini (golang):

https://github.com/codegangsta/martini#next

    // log before and after a request
    m.Use(func(c martini.Context, log *log.Logger){
      log.Println("before a request")

      c.Next()

      log.Println("after a request")
    })


I don't think this yields the current thread/routine though does it? I think what you are seeing here is closer to express':

  function(req, res, next) {
    console.log('before');
    next(); // go to the next middleware handler
    console.log('after the middleware stack has been traversed');  
  }


I think does yield as stated in docs. Go have coroutines so there is no need in generators.


That's using a callback, like express or connect does. What's new in koa is the use of js generators


Go doesn't need JS generators. It already handles execution flow correctly. It is not correct to assume the Node execution model holds everywhere; we've made a lot of great advances since the old event-based model was invented in the 70s. That actually wraps the full handler without any need to jump through event threading hoops, and is not "blocking", in the sense that the Node community uses the term. That's an out-of-the-box feature for a modern language.


> That's an out-of-the-box feature for a modern language.

Or for any Scheme for the last 30 years, but don't let that change your views on how "modern" you language is :)


"Everything" was invented by the 70s (and a lot in the 60s); unfortunately the huge stinking popularity of GUIs combined with relentless drum beats of the latest code being due out yesterday took us on a decades-long detour through what turned out to be some bad ideas (OO in the "model the physical world" sense, which GUI frameworks deceptively made appear to work, event-based systems which are simple spaghetti-code redux in the Dijkstra sense of "spaghetti code").


Compared to JavaScript, Scheme is a modern language!


It looks almost like if they rewrote express for generator functions

I can't wait to drop this in to one of my projects!


That's pretty much what they did (and connect, which was the foundation of express and since bought by senchalabs).


Wasn't connect written by senchalabs in the first place, not bought?


I think they funded its development, so yes and no.


So, does node support generators out of the box?


It's behind a flag (--harmony-generators) in 0.11 (current stable is 0.10, hence my "next generation" comment).


Does koa (or co) solve the problem with generators where

* stack traces of errors are useless? [1]

* missing catch filters/pattern matching i.e. catch (e) {} also captures type, reference and range errors i.e. "pokemon exception handling"?

[1]: http://spion.github.io/posts/analysis-generators-and-other-a...


yes, stack traces work now, as long as they aren't being thrown in a different event loop: https://github.com/koajs/koa/issues/117


Oops - I didn't mean thrown errors, I meant errors passed to the callbacks.

It doesn't seem like they are useful yet:

https://gist.github.com/spion/356bfc9cc1089edd2e3b


I have some questions about this:

1. The FAQ gives a political answer about the status of Express but I imagine that Express will not be actively maintained any more. Correct?

2. If focus is now on Koa, why the name change from Express when it is already a huge name for node frameworks?

3. If a new developer sees Express and Koa, would they immediately know which one is being focused on?

Basically I'm wondering why it couldn't be called Express 3.0 (or 4.0).


My guess is that because Express and Connect aren't really big frameworks changing something fundamental as the middleware API would break all backwards compatibility. So you'll end up with a different framework anyway. This way people that like generator middleware can pick koa and if you prefer the old style middleware you can still use Express.js.

I also see pull requests getting merged into Express.js on almost a daily base. So I am not really worried about it dying anything soon. Most of the road map items for express are about extracting it's features into separate modules as well. Which means they are aiming at making the Express core even smaller and less opinionated.


Express is still maintained, by a bunch of us, but personally I'll be focusing mostly on Koa. They're separate because conceptually Koa is quite different, the migration from the would-be Express 3.0 -> 4.0 would mean rewriting the app


I understand it's due to connect being bought by sencha. The FAQ states it's more like connect, with some express goodies moved to the middleware level.


But express was connect with some extra goodies on top. Surely this is an iteration upon express?

I guess I'm more concerned about the marketing of this framework as there's now two names for the same thing except one is newer than the other. As a dirty analogy - if jQuery started to support yields instead of function callbacks, do they change the name of the library?

Looking at the syntax of Koa, it's still express except it looks nicer because there's no callbacks. What was the reasoning for ditching the big name? It can't be just for that.


It looks like some important express-like things are missing though. For instance, there is no routing abstraction or rendering. I think you're right that Express is connect with extra goodies, but the most important of those are missing from koa. Although branding it as a 'next-generation web framework' definitely seems like they want to replace express.


If express was connect, since koa is basically a rewrite of connect using generators, doesn't it make sense to give it a new name?


Express isn't Connect. Does it honestly even matter or are you just finding something to nitpick?


Koa is only usable with >= 11.9 behind the --harmony flag, I doubt they'd want to release a new version of Express that most people can't/won't even use.


you can also use it with > 0.8 with https://github.com/TooTallNate/gnode


What's the star in "function *(){}" for ?

EDIT: Answer: that's how "generator functions" are recognized. http://wiki.ecmascript.org/doku.php?id=harmony:generators


Does node.js support the * though. I tried their example and getting this:

  app.use(function *(next){
                   ^
  SyntaxError: Unexpected token *
      at Module._compile (module.js:439:25)
      at Object.Module._extensions..js (module.js:474:10)
      at Module.load (module.js:356:32)
      at Function.Module._load (module.js:312:12)
      at Function.Module.runMain (module.js:497:10)
      at startup (node.js:119:16)
      at node.js:901:3


It requires node v0.11.3 or above and the --harmony-generators flag at launch.

Or use gnode, which will down-compile it to ES5 for current stable node.


You probably need the `--harmony-generators` or `--harmony` flag.


Thanks, I was wondering the same thing. "A function named star you say?" Heh :-)


Which Nodejs Web framework is the most popular in production? There are so many choices: http://nodeframework.com/

It seems Express and Connect? http://stackoverflow.com/questions/3809539/choosing-a-web-ap...


FTA, Koa is made by the same people who make Express.

And Express sits on top of Connect.


I'd guess Express. It's in use at quite a few high profile companies, and most other frameworks are just built on top of it.


Express is probably the most popular in terms of apps deployed, and sits on top of Connect.

Koa is likely to replace Connect [0].

[0]: https://twitter.com/tjholowaychuk/status/369868946989535232


Not sure I understand the semantics. I'm passed what looks like a continuation, but instead of calling it, I yield it?

What other values can I yield, and why would I want to?

Alternatively, couldn't the `next` object just be a plain continuation?


zimbatm's link to http://wiki.ecmascript.org/doku.php?id=harmony:generators was helpful here. https://wiki.python.org/moin/Generators seems to also have some useful background on where the semantics are coming from.


If TJ is on board that's the only information you need to know, you cant go wrong with any code that guy writes.


I often purposefully avoid TJ modules because many of them end up being unmaintained. Before using a TJ project check the outstanding pull requests: are there a large number of open useful looking PR's? Is there somebody besides TJ merging into master: aka has he delegated a maintainer?


Ryan left node a long time ago, people still use it, just because the original author isn't involved doesn't make it a bad project


That's right. I don't really care if you're actively involved in the project; I just want somebody you trust to be. Like any node shop we quite happily use a bunch of TJ modules.


There were a few of his projects going this way but he recently reached out for maintainers[1] and things are looking better now.

[1] https://medium.com/code-adventures/c819768a175f


if there's a project you want to maintain for him, just ask and he'll give you ownership. i help with koa and most of his more popular repos have multiple maintainers now, so don't worry.


I have utmost respect for TJ and his work but I am not a fan of his yoda style programming :(


haha I've grown to prefer it, sort of like regular conditionals vs postfix conditionals, you set up the expectation first:

if (user.isAuthenticated) doSomething()

vs

doSomething() if (user.isAuthenticated)

the first is less readable perhaps but I think it's more useful for a programmer. To each their own! Maybe some day I'll be convinced otherwise, I like it better for asserts too:

assert(200 = res.statusCode) assert('application/json' == res.headers['content-type'])

assert(res.headers['content-type'] == 'application/json')

looks weird to me now but maybe I'm just used to it


What do you mean by that? if (constant == variable) type conditions?



A similar convention, often seen within the node community: https://npmjs.org/doc/coding-style.html#Comma-First Personally, I find this ugly with very little benefit. It seems awkward to edit.


Comma first is a great convention, it allows you to easily comment out an item in a list while debugging. for example:

  var test = [
              "firstitem"
              , "seconditem"
              //, "thriditem_commented_out"
              //,  "fourthitem_should_also_be_commented_out"
           ]
Otherwise you have to do this:

  var test = [
               "firstitem",
               "seconditem"//,
               //"thriditem",
               //"fourthitem"
           ]
It's just a lot more cognitive overhead to not put the comma first.


That's not true because the spec for JS allows the trailing comma. IE is the only browser that doesn't follow this. So if you are doing Node dev, the trailing comma is harmless.


You realise it's the opposite for the first item, right? Code easier to read (and thus understand) is what everyone should aim for.


Agreed, I follow this styleguide: https://github.com/felixge/node-style-guide


I did this for a while, it's easier to spot missing commas and allows you to comment out lines (besides the first line) but I switched back because it was annoying to align :/


But you do know why this style exists and what benefits it has?


Hmm, I've read reasons why you could code like this, but personally I would never make my code more complicated to read just to prevent errors that I can prevent with other methods, like having tests, for example. I would assume after someone has been coding for a decent amount of time, they would have the experience to spot declaration/assignment mistakes and shouldn't have to rely on yoda conditionals to prevent this. Perhaps there's other reasons I'm not aware of, and am not seeing the light because of that, care to share your thoughts?


I adopted this in my C days. Sure some compilers catch accidental assignment but not all and it could be disabled. As a defensive programming style I personally think the readability concerns were outweighed by the safety benefits. Not everyone agrees and I adapt my style to the project I'm working on.


Wikipedia gives an explanation: http://en.wikipedia.org/wiki/Yoda_conditions Seems kind of meh, especially if you're writing javascript when keywords like undefined can be redefined with no effect.


In most environments, writing something like `if (x = 5)` will generate a warning.

E.g. if you use JSHint, you'd get:

"Expected a conditional expression and instead saw an assignment."

Nowadays, there usually isn't any benefit in using yoda conditions.


I don't, and I'd be really grateful if anyone would enlighten me on the matter. Please excuse my ignorance!


If you forget to type a 2nd '=', putting a constant as the left-hand-side will allow the runtime to error instead of treating the expression like an accidental assignment with potentially disastrous side-effects.


it goes back further than this..

in compiled languages it is a compile time error. So you don't run through 1/2 of your application before you run into it. Instead it shows up as soon as you run make/gcc/g++/etc.


In some languages sometimes but in general I think that's the use case for yoda code.


It does seem strange, is there a reasoned argument for why this can be better?


The two reasons I've heard are preventing accidental variable assignment and preventing null references. Personally, I don't think either of those things outweigh the readability issue.


Can someone explain why this is better than for example Express?


One way: It leverages generators, which helps in avoiding callback hell (http://blog.alexmaccaw.com/how-yield-will-transform-node) Koa is written by the same author as express.


It's made by the same people who made Express. It seems like it's an off-shoot that uses generators, something that would be difficult to do in Express.


So much for "above the fold."



It's funny -- I love node.js for pretty much everything except for web frameworks. IMO Express, Koa, Sails, and Meteor are all lacking some kind of je ne sais quoi... maybe I should try my hand at one as an open source project...? Anyone have any good resources about framework design?


I always felt that I didn't understand the node way of work, because all frameworks feel to me like they are missing something, like they are ignoring the good ideas built in other frameworks. Or maybe they are too functional for my OOP head.

I had to work with express, and one thing that I missed was having a Response object where you build your response and then pass back to the framework at the end of the request. So I built my own proof-of-concept-framework to understand why others don't do it (maybe it was just not possible).

Many people will tell you that there are a thousand frameworks out there, go contribute to one of those instead of creating more noise. For me doing a framework was a great way of learning the internals of node, the kind of things that frameworks are designed to hide away from you. Go for it, start your own open source framework and put your ideas into practice. The ecosystem is still maturing.


Check out Sails.js. It's under active development, but I've used it for a few things and find it totally fantastic:

http://sailsjs.org/


Yea Sails is awesome but I feel like the devs have been putting the community on the back burner lately. Its ORM is off to a good start but I find myself writing a bunch of hard to maintain SQL because of the things yet to be implemented, like joins. Also, Windows support could use a ton more testing/attention.


I haven't touched it ever since I saw you can create records with GET requests by default. Did they ever fix that?


That has always been a config setting that should absolutely be turned off.


Is it default? I remember seeing the screencast when it was first gaining traction and immediately dismissing it. That should be something that isn't even included tbh.


I think the benefits it provides outweighs the slight chance that someone would ship code to production with it turned on.


I agree. It has been extremely useful during development


lol I listed Sails though--my problem with sails was that their website promised tomes upon tomes of documentation; come to find out the copy on the website is all boilerplate and none of the docs have been completed yet.


Does anyone have a good read on generators? I have no idea what that is.



If anybody finds / does a benchmark, please link it here.


TJ just updated express' benchmarks to match koa's. here are the results on my computer: https://gist.github.com/jonathanong/8065724


there's a silly benchmark in the repo: https://github.com/koajs/koa#benchmarks

but there aren't any comparisons yet.



Python has had generators since 2.2, where as they are just landing in js/node.js.


Yeah, strangely enough not all languages/libraries develop functionality at the same time. It's weird, I know.


Python developers always whine about doing their best.

Node developers go home and fuck the prom queen.


AND the queens name happens to be Rosie Palm




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: