如何缓存通过Ajax加载的文件-JavaScriptNode JS

问题描述

我正在开发一个应用程序,其中我要通过https.get()中的node js加载pdf文件,并将数据分块发送到前端。它工作得很好,我这样做的原因是,有时我会从远程服务器加载pdf,这会导致CORS问题,因此我编写了一个简单的代理为我处理它。它运作良好,但问题是,每当我从前端发出请求时,都会重新加载pdf,并每次加载它。我想做的是,当首次加载pdf文件时,我应该将其缓存在前端或后端,然后在每次刷新页面时从缓存中加载它。

The proxy written in Node JS

读取前端的文件

const url = "http://localhost:8003/pdf-cors";
const file = "https://veraviafit.com/wp-content/uploads/2018/11/N2RPlan-3-1.pdf";
fetch(`${url}?file=${file}`).then(async(response) => {
  const reader = response!.body!.getReader();
  const stream = new ReadableStream({
    start(controller) {
      // The following function handles each data chunk
      function push() {
        // "done" is a Boolean and value a "Uint8Array"
        reader.read().then((r) => {
          // console.log(r);
          const {
            done,value
          } = r;
          console.log("VALUE ---> ",value);
          // Is there no more data to read?
          if (done) {
            // Tell the browser that we have finished sending data
            controller.close();
            return;
          }
          // console.log(value);
          // Get the data and send it to the browser via the controller
          controller.enqueue(value);
          push();
        });
      };
      push();
    }
  });

  return new Response(stream,{
    headers: {
      "Content-Type": "text/html"
    }
  });
});

解决方法

从lodash中检查备忘录功能。如果不想包含lodash,可以很容易地实现这样的功能。

https://lodash.com/docs/4.17.15#memoize

,

我找到了一个可行的解决方案,可以完美地减少加载时间。因此,第一次加载this pdf花费了2.5分钟(实际上取决于互联网速度),第二次重新加载时,仅花费了54秒来加载pdf在缓存时,我所要做的就是设置响应缓存头,它实际上将缓存加载的数据。您可以访问this question来查看其工作原理,我将其设置为this in my proxy code

为了加载缓存动态文件,我让文件第一次加载并使用指定的缓存“键”保存,然后将整个块写入该文件。加载文件后,当我重新加载页面并请求同一个文件时,我正在从文件中发回数据,而不是在每次调用时都加载外部资源。它以毫秒为单位加载文件。