像chatpGPT显示文字一样.主要是服务器流式返回数据.前端用for await读取response.body
<button id="fetchjson" onclick="FetchJSON()">fetch json看console与network</button>
<button id="fetchstream" onclick="FetchStream()">fetch stream</button>
<div id="outputBox"></div>
<script>
async function FetchJSON(){
console.log('触发请求')
let response=await fetch('/json')
console.log('got response headersnow wating for the body')
let myObject=await response.json()
console.log('turned the JSON in an object')
console.log(myObject)
}
async function FetchStream(){
outputBox.textContent=''
let response=await fetch('/json')
const decoder=new TextDecoder('utf-8')
for await (const value of response.body){
const chunk=decoder.decode(value)
console.log('======chunk',chunk);
outputBox.textContent+=chunk
}
}
</script>
const http = require('http');
const fs = require('fs');
const path = require('path');
/** 创建一个服务器 */
const server = http.createServer((req, res) => {
//serve HTML
if (req.method === 'GET' && req.url === '/') {
const filePath = path.join(__dirname, 'index.html');
fs.readFile(filePath, (err, data) => {
res.writeHead(200, { 'Content-type': 'text/html' })
res.end(data);
});
return
}
//serve JSON,but slowly
if (req.method === 'GET' && req.url === '/json') {
res.writeHead(200, { 'Content-type': 'application/json' })
//set up a readable stream
const filePath = path.join(__dirname, 'data.json')
const stream = fs.createReadStream(filePath, { 'encoding': 'utf8' });
//read the stream on byte (character) at a time and send it to the client
stream.on('readable', function () {
const interval = setInterval(() => {
const data = stream.read(2);
//这里的stream.read(1)如果填1的话,遇到中文传输一个字,遇到英文也是一个字母
console.log('======data', data);
if (data !== null) {
res.write(data);
} else {
clearInterval(interval);
res.end();
}
}, 2000);
})
return
}
});
const PORT = 3000
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`)
})