欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Egg.js構建一個stream流式接口服務實現(xiàn)詳解

 更新時間:2023年09月20日 14:15:34   作者:天問  
這篇文章主要為大家介紹了Egg.js構建一個stream流式接口服務實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

引言

經(jīng)常需要用到 stream 流式接口服務,比如:大文件下載、日志實時輸出等等。本文將介紹如何使用Egg.js構建一個 stream 流式接口服務。

Egg.js Stream API

一、準備工作

目錄結構:

app/
    /controller
        index.js
        test.txt
        test.sh
  • index.js 控制器
  • test.txt 測試文件,最好是20M以上的文件,這樣才能看出流式返回的效果
  • test.sh 測試腳本,用于實時輸出日志的測試腳本

二、流式文件處理

  • controller/index.js 文件內(nèi)容如下:
'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 文件內(nèi)容如下:
'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 文件內(nèi)容如下:
#!/usr/bin/env sh
set -e
int=1
while(( $int<=10 ))
do
    echo $int
    sleep 2
    let "int++"
done

四、測試

前端使用 fetch 方法進行測試,為什么不用 axios ?因為 axios 是基于 XMLHttpRequest 的,不支持流式接口。 具體實現(xiàn)請參考:前端實現(xiàn) stream 流式請求

以上就是Egg.js構建一個stream流式接口服務實現(xiàn)詳解的詳細內(nèi)容,更多關于Egg.js構建stream流式接口服務的資料請關注腳本之家其它相關文章!

相關文章

最新評論