經常需要用到 stream 流式接口服務,比如:大文件下載、日志實時輸出等等。本文將介紹如何使用Egg.js構建一個 stream 流式接口服務。
一、準備工作
目錄結構:
app//controllerindex.jstest.txttest.sh
- index.js 控制器
- test.txt 測試文件,最好是20M以上的文件,這樣才能看出流式返回的效果
- test.sh 測試腳本,用于實時輸出日志的測試腳本
二、流式文件處理
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;
三、流式日志處理
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;
controller/test.sh
文件內容如下:
#!/usr/bin/env shset -eint=1
while(( $int<=10 ))
doecho $intsleep 2let "int++"
done
四、測試
前端使用 fetch 方法進行測試,為什么不用 axios ?因為 axios 是基于 XMLHttpRequest
的,不支持流式接口。 具體實現請參考:前端實現 stream 流式請求
歡迎訪問:天問博客