nodejs逐字读取文件示例

像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}`)
})


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值