Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

javascript - node js - understanding variable scopes

I am fairly new to node.js and trying to get my head around the asynchronous processing loop etc.

So let's assume I have an array var counter = [];defined at the top of my server.js file

Then I have a POST handler as follows

app.post("/test_post", function(req, res) {
    console.log(req.body);
    counter ++;
})

I am trying to understand the scope of the counter variable - Will it be different for every client or will it be common across clients.

Also, I am looking for a way to increment counter for the same client, so in other words, I'd like a counter for each visiting client.

How can I achieve this? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am trying to understand the scope of the counter variable - Will it be different for every client or will it be common across clients.

It will be common across clients since you are defining it globally.

Also, I am looking for a way to increment counter for the same client, so in other words, I'd like a counter for each visiting client.

Basically what you need to do is to listen on connection & disconnection of every client and save the counter in the respective client object.

Have a look at this implementation it may help you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...