mirror of
https://github.com/koajs/examples.git
synced 2026-01-18 14:38:19 +00:00
52 lines
1.0 KiB
JavaScript
52 lines
1.0 KiB
JavaScript
|
|
/**
|
|
* 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.body.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');
|