Skip to content
/ koa Public
forked from koajs/koa

Expressive middleware for node.js using generators

License

Notifications You must be signed in to change notification settings

xycloud/koa

 
 

Repository files navigation

koa middleware framework for nodejs

gitter NPM version build status Test coverage

Expressive HTTP middleware for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream. Koa's use of generators also greatly increases the readability and robustness of your application.

Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~550 SLOC codebase. This includes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.

Koa is not bundled with any middleware.

Installation

$ npm install koa

Koa is supported in node v4+ and node v0.12 with the --harmony-generators or --harmony flag.

Koa v2

Koa v2 is currently released with the next tag (meaning it will not be marked as latest). You can install it with semver:

npm install koa@2

In this new version, the middleware function signature completely changes in favor of ES2015-2016 syntax:

// Koa application is now a class and requires the new operator.
const app = new Koa();

// uses async arrow functions
app.use(async (ctx, next) => {
  try {
    await next(); // next is now a function
  } catch (err) {
    ctx.body = { message: err.message };
    ctx.status = err.status || 500;
  }
});

app.use(async ctx => {
  const user = await User.getById(ctx.session.userid); // await instead of yield
  ctx.body = user; // ctx instead of this
});

Although deprecated, the older, generator-based middleware signature will still work in v2 via koa-convert and will be removed in v3.

To learn more about Koa v2, follow this issue or read the docs here: https://github.com/koajs/koa/tree/v2.x/docs.

Community

Getting started

  • Kick-Off-Koa - An intro to koa via a set of self-guided workshops.
  • Workshop - A workshop to learn the basics of koa, Express' spiritual successor.
  • Introduction Screencast - An introduction to installing and getting started with Koa

Example

var koa = require('koa');
var app = koa();

// logger

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

// response

app.use(function *(){
  this.body = 'Hello World';
});

app.listen(3000);

Running tests

$ make test

Authors

License

MIT

About

Expressive middleware for node.js using generators

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 98.9%
  • Other 1.1%