forked from koajs/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (38 loc) · 989 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Module dependencies.
*/
var logger = require('koa-logger');
var serve = require('koa-static');
var parse = require('co-busboy');
var koa = require('koa');
var fs = require('fs');
var app = koa();
var os = require('os');
var path = require('path');
// log requests
app.use(logger());
// custom 404
app.use(function *(next){
yield next;
if (this.body || !this.idempotent) return;
this.redirect('/404.html');
});
// serve files from ./public
app.use(serve(__dirname + '/public'));
// handle uploads
app.use(function *(next){
// ignore non-POSTs
if ('POST' != this.method) return yield next;
// multipart upload
var parts = parse(this);
var part;
while (part = yield parts) {
var stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
part.pipe(stream);
console.log('uploading %s -> %s', part.filename, stream.path);
}
this.redirect('/');
});
// listen
app.listen(3000);
console.log('listening on port 3000');