-
Notifications
You must be signed in to change notification settings - Fork 741
/
Copy pathapp.js
51 lines (36 loc) · 1.04 KB
/
app.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
/**
* Module dependencies.
*/
const logger = require('koa-logger');
const serve = require('koa-static');
const koaBody = require('koa-body');
const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
const os = require('os');
const path = require('path');
// log requests
app.use(logger());
app.use(koaBody({ multipart: true }));
// custom 404
app.use(async function(ctx, next) {
await next();
if (ctx.body || !ctx.idempotent) return;
ctx.redirect('/404.html');
});
// serve files from ./public
app.use(serve(path.join(__dirname, '/public')));
// handle uploads
app.use(async function(ctx, next) {
// ignore non-POSTs
if ('POST' != ctx.method) return await next();
const file = ctx.request.files.file;
const reader = fs.createReadStream(file.path);
const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
reader.pipe(stream);
console.log('uploading %s -> %s', file.name, stream.path);
ctx.redirect('/');
});
// listen
app.listen(3000);
console.log('listening on port 3000');