Skip to content

白屏如何排查

和首屏加载优化相关,但不全相关

白屏的原因有哪些?

加载东西过多,堆栈会有什么变化?

cdn缓慢的原因有哪些?

场景设计:类似GPT的应用

如何做流式输出

法一:在后端做定时发送进行模拟

js
//client
const url = "http://localhost:3000/stream";

const loadData = async () => {
  try {
    const response = await fetch(url, {
      method: "POST",
    });

    const reader = response.body.getReader();
    const textDecoder = new TextDecoder();
    let data = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log("\nData loading finished");
        break;
      }

      const chunk = textDecoder.decode(value);
      data += chunk;
      console.log(chunk); // 实时显示收到的数据块
    }
  } catch (error) {
    console.error("Request failed", error);
  }
};

loadData();


//server
const express = require("express");
const app = express();

app.post("/stream", (req, res) => {
  res.setHeader("Content-Type", "text/plain");
  res.setHeader("Transfer-Encoding", "chunked");

  const text = "This is a sample response that will be sent in chunks.";
  let index = 0;

  const sendNextChunk = () => {
    if (index < text.length) {
      const chunk = text.substring(index, index + 5); // 例如每次发送5个字符
      res.write(chunk);
      index += 5;
      setTimeout(sendNextChunk, 100); // 控制每个块发送的速度
    } else {
      res.end();
    }
  };

  sendNextChunk();
});

app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});

类似大文件上传,顺便直接写一个大文件上传吧:

法二:前端等获取后做切片

多人访问如何做内容隔离

不能只绑定user id,因为可能有一个用户开启了多个窗口在同时使用gpt。

高维数组去重

面试时写的复杂了...

最简单的:

js
let log = console.log.bind(console);
let arr = [1, 2, [3, 4], [8, 9, [10, [11]]], 7, 6];
let flattened = arr.flat(Infinity).sort((a, b) => a - b);
log(flattened);

最中规中矩好懂的写法:

js
let log = console.log.bind(console);

function flattern(arr) {
  let R = [];
  // element
  if (!Array.isArray(arr)) {
    return [arr];
  }
  // array
  for (let a of arr) {
    R = [...R, ...flattern(a)];
  }
  return R;
}

function removeDuplicate(arr) {
  if (!Array.isArray(arr)) {
    return;
  }
  let flatterned = flattern(arr);
  let uniqued = [...new Set(flatterned)];
  let res = uniqued.sort((a, b) => a - b);
  return res;
}

let arr = [1, 2, [1, 2, 3, [6, 7]], 4, 5];
let res = removeDuplicate(arr);
log(res);

面试时写的:

js
let log = console.log.bind(console);

function flatten(arr) {
  let res = arr.reduce((acc, curr) => {
    if (Array.isArray(curr)) {
      acc = acc.concat(flatten(curr));
    } else {
      acc = acc.concat(curr);
    }
    return acc;
  }, []);
  return res;
}

function removeDuplicate(arr) {
  if (!Array.isArray(arr)) {
    return;
  }
  let flattened = flatten(arr);
  let uniqued = [...new Set(flattened)];
  uniqued.sort((a, b) => a - b);
  return uniqued;
}

// let arr = [2, 3, 4, [2, [1]]];
let arr = [1, 2, [3, 4], [8, 9, [10, [11]]], 7, 6];

let res = removeDuplicate(arr);
log("res", res);