1

I have been designing a web app in node.js with express and mongoDB, and it just occurred to me that any variables that I declare within the script will be accessible to all users because node runs as a single thread. For example, I am using a server-side form validator, here is a piece of it:

app.post('/purchase', requireLogin, function(req, res) {
var b = req.body;
var ee;
for (i in b) {
    if (!validatePresenceOf(b[i])) {
        var ee="Please fill out all fields.<br />\n";
    }
}

var exp = b.exp_mm+"/"+b.exp_yy;
var d = /^(0[1-9]|1[012])[- /.]\d\d$/
if (!d.test(expiration)) {
    ee+="Expiration date is invalid.<br />\n"
}

if (!isValidCreditCard(b.card_type, b.card_num)) {
    ee+="Credit card number is invalid.<br />\n";
}
});

I am wondering if another user makes a purchase at almost the same time, could variable b be redefined by a second request before the validator finishes? If it can, then what would be the best way around this, and will this happen every time I declare a variable? It seems like this could cause some security issues in case a variable is changed before a process is completed.

Thanks!

Ben
  • 63
  • 1
  • 3
  • 2
    It is indeed single threaded. This means that only once piece of js code can run at once. So these problems you imagine (the function running twice in parallel) can not occur because only one block of code can run at a time – Raynos Sep 12 '11 at 20:24
  • @Raynos there's also the matter of lexical scope ;) – jcolebrand Sep 12 '11 at 20:36

1 Answers1

2

No, that variable won't be shared because it will still have lexical scope only to the process operating because of function closure.

The fact that you're declaring it with var b within the function defines it to have that lexical scoping.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
  • Ok thank you! I was worried I would have to go back and assign a bunch of random variables to req.session or something. – Ben Sep 12 '11 at 20:27
  • Nope, but those would suffer the same fate. This is all about scope, which is always a good thing to read up on. Additionally the word "closure" as it is used in javascript. – jcolebrand Sep 12 '11 at 20:27