nest中获取content-length

2024-08-22 21:04
文章标签 获取 length content nest

本文主要是介绍nest中获取content-length,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

mock项目中nest执行过程:

import { NestFactory } from '@nestjs/core'
import { Module, Req, Injectable, NestMiddleware, NestInterceptor, ExecutionContext, Res, Header, CallHandler, Controller, Get, MiddlewareConsumer, NestModule } from '@nestjs/common'
import { AsyncLocalStorage } from 'async_hooks'
import { Observable, throwError } from 'rxjs'
import { catchError, tap, finalize } from "rxjs/operators"
import { APP_INTERCEPTOR } from '@nestjs/core'
import { Request, Response } from 'express'// 模拟异步操作链数据存储
@Injectable()
class ClsService {als: AsyncLocalStorage<Record<string, unknown>>constructor() {this.als = new AsyncLocalStorage()}get(key: string) {return this.als.getStore()?.[key]}set(key: string, value: unknown) {if (this.als.getStore()) {(this.als.getStore() as Record<string, unknown>)[key] = value}}
}// 模拟中间件
@Injectable()
class ClsMiddleWare implements NestMiddleware {constructor(private ClsService: ClsService) {console.log('Middleware registry')}async use(req: Request, res: Response, next: () => void) {const realIp = req.headers['x-real-ip'] as string || '0.0.0.0'console.log('Middleware executed, IP:', realIp)console.log('Middleware enter', this.ClsService.als.getStore())this.ClsService.als.run({ ip: realIp }, () => {next()setTimeout(() => {console.log('Middleware timeout', this.ClsService.als.getStore())}, 10)console.log('Middleware exit 1', this.ClsService.als.getStore())})console.log('Middleware exit', this.ClsService.als.getStore())}
}// 模拟拦截器
@Injectable()
class LoggingInterceptor implements NestInterceptor {constructor(private ClsService: ClsService) {console.log('Interceptor registry')}intercept(context: ExecutionContext, next: CallHandler): Observable<any> {console.log('Interceptor executed')return next.handle().pipe(tap((result) => {let req = context.switchToHttp().getRequest() as Requestlet res = context.switchToHttp().getResponse()let cl = (res as Response).get("content-length")console.log("sync===", cl, res.get("content-length"), res.headersSent, result)setTimeout(() => {console.log("===async===", cl, res.get("content-length"), res.headersSent, result)}, 0)}),catchError((error) => {// console.log("interceptor", error)return throwError(() => error)}),finalize(() => {// console.log("entry finalize===")}))}
}// 模拟控制器
@Controller('example')
class ExampleController {constructor() { }@Get("")test() {console.log('Controller method executed')return { message: 'this is nest return' }}@Get("express")express(@Req() req: Request,@Res() res: Response) {console.log('Controller method executed')res.send({message: "this is express send"})}@Get("/stream")getExample(@Req() req: Request,@Res() res: Response) {console.log('Controller method executed')let i = 1res.contentType("application/octet-stream")setInterval(() => {res.write(Buffer.from("abcdefg"))if (i++ > 10) {// stream.close()res.end()}}, 1000)}
}// 应用模块
@Module({imports: [],controllers: [ExampleController],providers: [ClsService,{provide: APP_INTERCEPTOR,useClass: LoggingInterceptor,},],
})
export class AppModule implements NestModule {configure(consumer: MiddlewareConsumer) {consumer.apply(ClsMiddleWare).forRoutes('*') // 应用到所有路由}
}// 启动应用
async function bootstrap() {const app = await NestFactory.create(AppModule)await app.listen(3000)
}bootstrap()

此时访问:http://localhost:3000/example

此时控制台输出的内容为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== undefined undefined false { message: 'this is nest return' }
===async=== undefined 33 true { message: 'this is nest return' }
Middleware timeout { ip: '0.0.0.0' }

这里可以得到4个信息

  • 在宏任务0的异步阶段响应头已经发送
  • 在未发送时是无法获取content-length的,发送后可获取到
  • get(“content-length”)获取的是快照
  • 无论在哪个阶段,使用return的方式返回的数据在interceptor中是可以获取的

接下来访问:http://localhost:3000/example/express

此时控制台输出的内容为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== 34 34 true undefined
===async=== 34 34 true undefined
Middleware timeout { ip: '0.0.0.0' }

可以看到直接send的情况,同步时已经将响应发送完毕了,此时同步异步都可以拿到headers


接下来访问:http://localhost:3000/example/stream

此时控制台输出的内容为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== undefined undefined false undefined
===async=== undefined undefined false undefined
Middleware timeout { ip: '0.0.0.0' }

可以看到直接send的情况,无论是同步还是延时0的宏任务都是拿不到数据的

此时在interceptor中增加:

  res.on("finish", () => {console.log("===response finished", cl, res.get("content-length"), res.headersSent, result)})

此时的控制台输出为:

Middleware executed, IP: 0.0.0.0
Middleware enter undefined
Middleware exit 1 { ip: '0.0.0.0' }
Middleware exit undefined
Interceptor executed
Controller method executed
sync=== undefined undefined false undefined
===async=== undefined undefined false undefined
Middleware timeout { ip: '0.0.0.0' }
===response finished undefined undefined true undefined

可以看到面对数据流的情况,即使是发送完成也无法获取到content-length 这种情况目前可以暂不考虑。


目前得到的结论是,如果想稳定拿到contentLength,最好是监听finish事件,即

   res.on("finish", () => {console.log("===response finished", res.get("content-length"))})// 可以优化为:res.once("finish", () => {console.log("===response finished", res.get("content-length"))})

鉴于闭包的形式可能引起的内存泄漏的问题,所以最终采用计算result的方式

  let res = context.switchToHttp().getResponse()let contentLength = res.get("content-length")if (!contentLength && result) {try {contentLength = Buffer.from(JSON.stringify(result)).length ?? 0} catch (error) {contentLength ??= 0}}

这篇关于nest中获取content-length的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1097393

相关文章

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

MySQL 获取字符串长度及注意事项

《MySQL获取字符串长度及注意事项》本文通过实例代码给大家介绍MySQL获取字符串长度及注意事项,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 获取字符串长度详解 核心长度函数对比⚠️ 六大关键注意事项1. 字符编码决定字节长度2

python3如何找到字典的下标index、获取list中指定元素的位置索引

《python3如何找到字典的下标index、获取list中指定元素的位置索引》:本文主要介绍python3如何找到字典的下标index、获取list中指定元素的位置索引问题,具有很好的参考价值,... 目录enumerate()找到字典的下标 index获取list中指定元素的位置索引总结enumerat

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

SpringBoot服务获取Pod当前IP的两种方案

《SpringBoot服务获取Pod当前IP的两种方案》在Kubernetes集群中,SpringBoot服务获取Pod当前IP的方案主要有两种,通过环境变量注入或通过Java代码动态获取网络接口IP... 目录方案一:通过 Kubernetes Downward API 注入环境变量原理步骤方案二:通过

使用Python实现获取屏幕像素颜色值

《使用Python实现获取屏幕像素颜色值》这篇文章主要为大家详细介绍了如何使用Python实现获取屏幕像素颜色值,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 一、一个小工具,按住F10键,颜色值会跟着显示。完整代码import tkinter as tkimport pyau

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

使用Python获取JS加载的数据的多种实现方法

《使用Python获取JS加载的数据的多种实现方法》在当今的互联网时代,网页数据的动态加载已经成为一种常见的技术手段,许多现代网站通过JavaScript(JS)动态加载内容,这使得传统的静态网页爬取... 目录引言一、动态 网页与js加载数据的原理二、python爬取JS加载数据的方法(一)分析网络请求1

通过cmd获取网卡速率的代码

《通过cmd获取网卡速率的代码》今天从群里看到通过bat获取网卡速率两段代码,感觉还不错,学习bat的朋友可以参考一下... 1、本机有线网卡支持的最高速度:%v%@echo off & setlocal enabledelayedexpansionecho 代码开始echo 65001编码获取: >