Egg.js构建一个stream流式接口服务

经常需要用到 stream 流式接口服务,比如:大文件下载、日志实时输出等等。本文将介绍如何使用Egg.js构建一个 stream 流式接口服务。

Egg.js Stream API

一、准备工作

目录结构:

app/
    /controller
        index.js
        test.txt
        test.sh
  1. index.js 控制器
  2. test.txt 测试文件,最好是20M以上的文件,这样才能看出流式返回的效果
  3. test.sh 测试脚本,用于实时输出日志的测试脚本

二、流式文件处理

  1. controller/index.js 文件内容如下:
'use strict';

const Controller = require('egg').Controller;
const { createReadStream } = require('fs');
const { join } = require('path');

class HomeController extends Controller {

  async testStream() {
    const { ctx } = this;
    ctx.set('Content-Type', 'text/plain; charset=utf-8');
    const stream = createReadStream(join(__dirname, './test.txt'));
    ctx.body = stream;
  }

}

module.exports = HomeController;

三、流式日志处理

  1. controller/index.js 文件内容如下:
'use strict';

const Controller = require('egg').Controller;
const { createReadStream } = require('fs');
const { join } = require('path');
const { spawn } = require('child_process');

class HomeController extends Controller {

  async testStream() {
    ctx.set('Content-Type', 'text/plain; charset=utf-8');

    const shPath = join(__dirname, './test.sh');
    const stream = spawn('sh', [ shPath ]);
    ctx.body = stream.stdout;
  }

}

module.exports = HomeController;
  1. controller/test.sh 文件内容如下:
#!/usr/bin/env sh

set -e

int=1
while(( $int<=10 ))
do
    echo $int
    sleep 2
    let "int++"
done

四、测试

前端使用 fetch 方法进行测试,为什么不用 axios ?因为 axios 是基于 XMLHttpRequest 的,不支持流式接口。 具体实现请参考:前端实现 stream 流式请求


欢迎访问:天问博客

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值