[英]Persistent variables in nodeJS
我正在編寫一個節點應用程序,需要記住createServer()
回調的連接迭代中的數據。 有一種不涉及數據庫或文件r / w的簡單方法嗎? 我已嘗試在各個模塊甚至主腳本中創建對象,同時將它們傳遞給各種響應處理程序,但是對於每個連接,它們都會被刷新。
我的意思是:
require('http').createServer(function(req,res){
route(req,res,object);
}).listen(cp=80);
object={variable:0}
function route(req,res,object){
res.end();
console.log(object.variable);
object.variable=Math.floor(Math.random()*100);
}
在這種情況下, console.log
地拋出每個連接0
。 有沒有辦法創建全局變量,而不是跨模塊可用,但與var
不同的是持久性?
Node中的每個模塊都有自己的范圍,所以沒有, var Foo;
不會創建全局變量Foo。 從模塊內部使用global
對象。
更新:
require('http').createServer(function(req,res){
route(req,res,object);
}).listen(cp=8080);
object={variable:0}
global.foo = 'Bar'; // I added this
function route(req,res,object){
res.end();
console.log(object.variable);
console.log("foo = %s", global.foo); // I added this too
object.variable=Math.floor(Math.random()*100);
}
並且它也按預期記錄“foo = Bar”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.