Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否从代理返回http.ClientRequest?_Javascript_Node.js_Https_Proxy - Fatal编程技术网

Javascript 是否从代理返回http.ClientRequest?

Javascript 是否从代理返回http.ClientRequest?,javascript,node.js,https,proxy,Javascript,Node.js,Https,Proxy,我编写了一个小的helper函数,它(理论上)缓存来自https.get函数的调用,并在缓存命中时立即返回内容。否则,它将发送请求并将内容写入缓存。下面是一个简单的示例: const cache = new Map(); function createCacheProxy(obj, cache) { return new Proxy(obj, { apply: function(target, thisArgs, argumentList) { /

我编写了一个小的helper函数,它(理论上)缓存来自https.get函数的调用,并在缓存命中时立即返回内容。否则,它将发送请求并将内容写入缓存。下面是一个简单的示例:

const cache = new Map();
function createCacheProxy(obj, cache) {
    return new Proxy(obj, {
        apply: function(target, thisArgs, argumentList) {
            // [...]
            const callback = argumentList.slice(-1)[0]
            const hash = // calculate hash from parameters
            if(chache.has(hash)) {
                //[!] Confusion
                return callback(Readable.from([cache.get(hash)])) // Caller will get undefined
            } else {
                // [...] 
                // Write stuff to cache. I use a PassThrough stream for this. 
            // [...]
                return target(...argumentList) // Caller will get a valid ClientRequest      
            }
            // [...]
        }
    })
}

const proxy = createCacheProxy(https.get, cache);
const clientRequest = proxy("https://example.com", {...}, (res) => {...})
实际上,它可以工作,但我有一个大问题:如果缓存命中,我只调用回调函数,将缓存体作为可读流。代理的调用方将不会获得ClientRequest对象,因此整个过程毫无意义。另一方面,我不能仅仅返回一个新的ClientRequest,因为这将触发另一个不必要的http调用


有没有办法返回一个“完成”的ClientRequest对象,或者你有没有其他技巧可以让它像预期的那样工作?

也许我使用了错误的方法,或者我太笨了,但是由于没有人知道答案,我决定也缓存ClientRequest,并在缓存命中的情况下返回缓存版本。你可以在下面找到我的新版本。如果有人有更好的解决方案,请随时与我联系:)