跳到主要内容

2 篇博文 含有标签「fetch」

查看所有标签

在 Node.js 中为 fetch 配置代理

· 阅读需 1 分钟
1adybug
子虚伊人

Node.js 中,原生的 fetch API 并不直接支持代理功能。可以使用 node-fetch 库和 https-proxy-agent 库来实现通过代理服务器发送请求的功能:

import { HttpsProxyAgent } from "https-proxy-agent"
import fetch from "node-fetch"

// 代理服务器的URL
const proxyUrl = "http://your-proxy-server:port"

// 目标URL,即你想要通过代理服务器访问的URL
const targetUrl = "http://example.com"

// 配置代理服务器
const proxyAgent = new HttpsProxyAgent(proxyUrl)

// 使用fetch发起请求,通过代理服务器访问目标URL
fetch(targetUrl, { agent: proxyAgent })
注意

与原生的 fetch 不同,node-fetchresponse.json() 返回值类型为 Promise<unknown>

ReadAbleStream 转换为 ReadStream

· 阅读需 1 分钟
1adybug
子虚伊人
import { Readable } from "stream"

const reader = readAbleStream.getReader()

const readStream = new Readable({
read() {
reader.read().then(({ done, value }) => {
if (done) readStream.push(null)
else readStream.push(value)
})
},
})

async function* nodeStreamToIterator(stream: ReadStream): AsyncGenerator<Buffer, void, never> {
for await (const chunk of stream) yield chunk
}

function iteratorToStream(iterator: AsyncGenerator<Buffer, void, never>): ReadableStream {
return new ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next()

if (done) controller.close()
else controller.enqueue(value)
},
})
}
提示

2024 年 3 月 29 日更新

Node.js 中其实自带了转换的功能

import { Readable } from "stream"

async function main() {
const response = await fetch("http://example.com")
const readable = Readable.fromWeb(response.body as any)
}

main()