最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Persistent variables in nodeJS - Stack Overflow

programmeradmin3浏览0评论

I am writing a node app that needs to remember data across connection iterations of the createServer() callback. Is there a simple way that doesn't involve databases or file r/w? I've sofar attempted creating objects in the respective modules and even main script while passing them into various response handlers, however for every connection they are flushed.

What I mean by that:

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 is unsurprisingly throws 0 every connection in this case. Is there any way to create global variables, not in the sense of being available across modules, but persistent unlike var's?

I am writing a node app that needs to remember data across connection iterations of the createServer() callback. Is there a simple way that doesn't involve databases or file r/w? I've sofar attempted creating objects in the respective modules and even main script while passing them into various response handlers, however for every connection they are flushed.

What I mean by that:

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 is unsurprisingly throws 0 every connection in this case. Is there any way to create global variables, not in the sense of being available across modules, but persistent unlike var's?

Share Improve this question edited Jun 26, 2012 at 0:47 TERMtm asked Jun 25, 2012 at 23:17 TERMtmTERMtm 1,9433 gold badges24 silver badges30 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

Each module in Node has its own scope, so no, var Foo; does not create a global variable Foo. Use global object from inside the modules.

UPDATE:

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);
}

And it logs "foo = Bar" as expected as well.

发布评论

评论列表(0)

  1. 暂无评论