@PHPjedi

Как это написать на Koa?

Доброго времени суток. Я хотел переписать следующий код
spoiler
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/index.html'));
})

app.get('/audio', function(req, res) {
  const path = 'sample.mp3';
  const stat = fs.statSync(path);
  const fileSize = stat.size;
  const range = req.headers.range;

  if (range) {
    const parts = range.replace(/bytes=/, '').split('-');
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

    const chunksize = (end-start) + 1;
    const file = fs.createReadStream(path, {start, end});
    const head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'audio/mpeg',
    };

    res.writeHead(206, head);
    file.pipe(res);
  } else {
    const head = {
      'Content-Length': fileSize,
      'Content-Type': 'audio/mpeg',
    };
    res.writeHead(200, head);
    fs.createReadStream(path).pipe(res);
  }
});

app.listen(8000, function () {
  console.log('Listening on port 8000!');
});
с Express на Koa, но появлялись очень много ошибкок. Ошибка первая, скорее всего из-за Response ответов. Вторая ошибка возникала при fs.createReadStream(path).pipe(res);. Пожалуйста помогите решить проблему.
  • Вопрос задан
  • 172 просмотра
Решения вопроса 1
Negezor
@Negezor
Senior Shaurma Developer
Как то так.
const Koa = require('koa');
const Router = require('koa-router');

const fs = require('fs');
const { promisify } = require('util');

const fsStat = promisify(fs.stat).bind(fs);

const app = Koa();

const router = new Router();

router.get('/audio', async (context) => {
    const path = 'sample.mp3';
    const { size: filesize } = await fsStat(path);

    const range = context.get('range');

    context.type = 'audio/mpeg';

    if (!range) {
        context.length = filesize;
        context.body = fs.createReadStream(path);

        return;
    }

    const [startPart, endPart] = range.replace(/bytes=/, '')
        .split('-');

    const start = parseInt(startPart, 10);
    const end = endPart
        ? parseInt(endPart, 10)
        : filesize - 1;

    context.length = (end - start) + 1;
    context.status = 206;

    context.set({
        'Accept-Ranges': 'bytes',
        'Content-Range': `bytes ${start}-${end}/${filesize}`
    });

    context.body = fs.createReadStream(path, {
        start,
        end
    });
});

app
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(8000, () => {
    console.log('Listening on port 8000!');
});
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы