gpt4 book ai didi

node.js - 带有缓存的nodejs node-http-proxy设置

转载 作者:搜寻专家 更新时间:2023-10-31 23:38:34 26 4
gpt4 key购买 nike

我正在尝试使用缓存设置 node-http-proxy 模块 node-http-proxy module .我已经设法配置 node-http-proxy 来完成我在代理调用方面需要做的事情,但我想找到一种方法来缓存其中一些调用。

我目前的代码如下(省略了一些配置引导):

var http = require('http');
var https = require('https');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var fs = require('fs');

var handler = function(req, res) {
proxy.web(req, res, {target: 'http://localhost:9000'});
};

var server = http.createServer(handler).listen(config.children.http.port, function() {
console.log('Listening on port %d', server.address().port);
});

var secure = https.createServer(config.children.https.options, handler).listen(config.children.https.port, function() {
console.log('Listening on port %d', secure.address().port);
});

在处理程序函数中,我希望能够以某种方式捕获代理从“目标”读取的内容,并将其流式传输到 fs.createWriteStream('/somepath') 中,然后再将其通过管道传输到 res。然后我会修改我的函数来做一些事情:

var handler = function(req, res) {
var path = '/somepath';
fs.exists(path, function(exists) {
if(exists) {
console.log('is file');
fs.createReadStream(path).pipe(res);
} else {
console.log('proxying');
// Here I need to find a way to write into path
proxy.web(req, res, {target: 'http://localhost:9000'});
}
});
};

有人知道怎么做吗?

最佳答案

问题的答案最终变得非常简单:

var handler = function(req, res, next) {

var path = '/tmp/file';
fs.exists(path, function(exists) {
if(exists) {
fs.createReadStream(path).pipe(res);
} else {
proxy.on('proxyRes', function(proxyRes, req, res) {
proxyRes.pipe(fs.createWriteStream(path));
});
proxy.web(req, res, {target: 'http://localhost:9000'});
}
});
};

关于node.js - 带有缓存的nodejs node-http-proxy设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25855628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com