express readline 返回逐行文件数据,fetch如何接收,求助大佬们
发布于 4 年前 作者 assmdx 4532 次浏览 来自 问答
	//服务端处理请求的代码: 
	 const fs = require('fs');
	 const readline = require('readline');
	 async getLog(req, res) {
	  const _this = this;
	  try {
		const { createReadStream } = fs;
		const log = '/opt/example.log'; // log 大小:40MB
		const readStream = createReadStream(log);
		const rl = readline.createInterface(readStream, res);
		rl.on("close", () => {
		  console.log("end");
		  readStream.close();
		  res.end();
		});
	  } catch (e) {
		logger.error("获取log失败", e);
		res.json(_this.fail(ERROR_PARAMETER, "获取日志失败,请稍后重试"));
	  }
	}
//浏览器fetch代码:
fetch(getLog)
    .then(async response => {
      const reader = response.body.getReader();
      do {
        let { done, value } = await reader.read();
        console.log(value);  //这里获取的只有一个undefined
        if (done) {
          break;
        }
      } while (true);
    })
    .catch(e => {
      console.error(e);
    });
4 回复

倒腾了半天终于解决了

	const fs = require('fs');
	 const readline = require('readline');
	 async getLog(req, res) {
	  const _this = this;
	  try {
		const { createReadStream } = fs;
		const log = '/opt/example.log'; // log 大小:40MB
		const readStream = createReadStream(log);
		readStream.pipe(res);
        readStream.on("end", () => {
           console.log("finished");
           res.end();
        });
	  } catch (e) {
		logger.error("获取log失败", e);
		res.json(_this.fail(ERROR_PARAMETER, "获取日志失败,请稍后重试"));
	  }
	}
   async queryLog() {
      let logs = "";
      fetch(getLog)
        .then(async response => {
          const reader = response.body.getReader();
          const decoder = new TextDecoder();
          do {
            let { done, value } = await reader.read();
            if (value) {
              let str = decoder.decode(value, { stream: true });
              logs = logs + str;
            }
            if (done) {
              break;
            }
          } while (true);
        })
        .catch(e => {
          console.error(e);
        });
    } 

去理解一下异步流程控制

@i5ting 感谢狼叔指点. 还有更高效优雅的写法吗 0.0?把浏览器端代码优化了一下:

	async queryLog() {
      let index = 0;
	  let logs = "";
      let response = await fetch(getLog);
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      do {
        let { done, value } = await reader.read();
        if (value) {
          let str = decoder.decode(value, { stream: true });
          logs = logs + str;
        }
        if (done) {
          break;
        }
      } while (true);
    }

@assmdx 有,用 eventemitter 来搞

回到顶部