簡體   English   中英

nodejs模塊是否跨多個HTTP請求緩存?

[英]Are nodejs modules cached across multiple HTTP requests?

nodejs文檔說

模塊在第一次加載后進行緩存。 這意味着(除其他外)每次調用require('foo')將獲得完全相同的返回對象,如果它將解析為同一個文件。

但它沒有指明范圍。 加載的模塊是否在當前HTTP請求中或多個HTTP請求中緩存多次調用require('module')?

對,他們是。

與其他常見的服務器環境(如PHP)不同,node.js服務器在請求完成后不會關閉。

假設您正在使用優秀的快速框架,也許這個例子將有助於理解差異:

... // setup your server

// do a route, that will show a call-counter
var callCount = {};

app.get('/hello/:name', function(request, response) {
  var name = request.params.name;
  callCount[name] = (callCount[name] || 0) + 1

  response.send(
    "Hello " + name + ", you invoked this " + callCount[name] + " times");
  });
});

當調用curl localhost:3000/hello/Dave ,每次后續呼叫都會收到更高的號碼。

第一個電話: Hello Dave, you invoked this 1 times

第二個電話: Hello Dave, you invoked this 2 times

... 等等 ...

因此,您的callCount將被該路由的任何請求修改。 它來自何處並不重要,它可以在您require任何模塊中定義。

無論如何,在服務器重新啟動時,將重置在任何模塊中定義的那些變量。 您可以通過將它們放入與您的node.js進程分開的Store來對抗它,例如Redis Store(請參閱node-redis ),文件系統上的文件或數據庫(如MongoDB) 最后,這取決於你。 您只需要知道數據的來源和去向。

希望有所幫助。

是。 同樣來自文檔:


    Multiple calls to require('foo') may not cause the module code to be executed 
    multiple times. This is an important feature. With it, "partially done" 
    objects can be returned, thus allowing transitive dependencies to be loaded 
    even when they would cause cycles. If you want to have a module execute code 
    multiple times, then export a function, and call that function.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM