4

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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How did you test? I just ran your code in Node and it works as expected.
As it turns out, I infact had a programming fluke where I created objects (sessions) and included a self destruct timeout in them. Apparently what happened is that, for the timers' value, I was inputting a math equation that apparently failed to parse. As a result, the variables would self destruct in under 318 milliseconds. Fun stuff. Also worth noting, you don't need to use the global namespace for this to work; neither do you need to declare the variable inside of main module if you just so happen to have the callback in a require. An update would be greatly appreciated, thanks again!
In this specific case no, you don't need a global. If you load modules async with require() than you do need as what you declared here (say, app.js) will not be visible in the modules. There you need to use a global object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.