当前位置: 首页 > article >正文

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


 

 


http://www.kler.cn/news/326674.html

相关文章:

  • Python中的`super()`函数:掌握面向对象编程的艺术
  • PHP“===”的意义
  • 工具类:JWT
  • 【AI学习】Lilian Weng:Extrinsic Hallucinations in LLMs(LLM 的外在幻觉)
  • TS-AI:一种用于多模态个体化脑区划分的深度学习管道,并结合任务对比合成|文献速递-Transformer架构在医学影像分析中的应用
  • 生产环境升级mysql流程及配置主从服务
  • YOLOv8改进 | 主干篇,YOLOv8改进主干网络为华为的轻量化架构GhostNetV1
  • C++ 左值右值引用梳理(一)
  • 蓝桥杯—STM32G431RBT6(RTC时钟获取时间和日期)
  • python 如何引用变量
  • LeetCode 每日一题 最佳观光组合
  • 水波荡漾效果+渲染顺序+简单UI绘制
  • Chromium 屏蔽“缺少 Google API 密钥,因此 Chromium 的部分功能将无法使用。”提示 c++
  • Conda 虚拟环境使用指南,python,anaconda,miniconda
  • MySQL InnoDB 事务commit逻辑分析
  • C++的new关键字
  • 如何在Android上运行Llama 3.2
  • 关于TrustedInstaller权限
  • c++-类和对象-设计立方体类
  • 每天学习一个技术栈 ——【Django Channels】篇(2)
  • ansible实现远程创建用户
  • [BUUCTF从零单排] Web方向 03.Web入门篇之sql注入-1(手工注入详解)
  • Java 编码系列:注解处理器详解与面试题解析
  • Uptime Kuma运维监控服务本地部署结合内网穿透实现远程在线监控
  • PostgreSQL的扩展Citus介绍
  • 非常全面的中考总复习资料-快速提升中考成绩!
  • 总结C/C++中内存区域划分
  • 点餐小程序实战教程14点餐功能
  • 心理咨询行业为何要有自己的知识付费小程序平台 心理咨询小程序搭建 集师saas知识付费小程序平台搭建
  • 遇到 Docker 镜像拉取失败的问题时该如何解决