Persistent variables in nodeJS

javascript, node.js

Solution

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.

Problem

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?

Original source