socketioMEANseed/www/node_modules/union/examples/simple/simple.js
www/node_modules/union/examples/simple/simple.jsRaw
1var fs = require('fs'),
2 path = require('path'),
3 union = require('../../lib'),
4 director = require('director'),
5 favicon = require('./middleware/favicon');
6
7var router = new director.http.Router();
8
9var server = union.createServer({
10 before: [
11 favicon(path.join(__dirname, 'favicon.png')),
12 function (req, res) {
13 var found = router.dispatch(req, res);
14 if (!found) {
15 res.emit('next');
16 }
17 }
18 ]
19});
20
21router.get('/foo', function () {
22 this.res.writeHead(200, { 'Content-Type': 'text/plain' });
23 this.res.end('hello world\n');
24});
25
26router.post('/foo', { stream: true }, function () {
27 var req = this.req,
28 res = this.res,
29 writeStream;
30
31 writeStream = fs.createWriteStream(__dirname + '/' + Date.now() + '-foo.txt');
32 req.pipe(writeStream);
33
34 writeStream.on('close', function () {
35 res.writeHead(200, { 'Content-Type': 'text/plain' });
36 res.end('wrote to a stream!');
37 });
38});
39
40router.get('/redirect', function () {
41 this.res.redirect('http://www.google.com');
42});
43
44router.get('/custom_redirect', function () {
45 this.res.redirect('/foo', 301);
46});
47
48router.get('/async', function () {
49 var self = this;
50 process.nextTick(function () {
51 self.req.on('end', function () {
52 self.res.end();
53 })
54 self.req.buffer = false;
55 });
56});
57
58server.listen(9090);
59console.log('union with director running on 9090');
60