Node ExpressJS – Becareful! A global variable will be shared between requests

  • fennng 

We all know that HTTP server is stateless, every time a request is processed, new instance of server handler will be created to serve the request. Each request is served by different handler instance, they don’t share context.

This is kind of true in C#.net, JAVA and other compile language unless static class and/or variable are used. You can create session to share the user context, that’s a different thing.

But in javascript, you have to pay extra attention.

I have a telegram bot called @fengfaqbot, which is used to auto reply/handle messages matched by rules. It sometimes will send auto response to another group which doesn’t have the rule setup. After tons of effort of investigation, I found that the problem is just caused by a missing let.

This lead to the payload variable become a global variable. And in some other place, this variable is modified, so something funny can just happened.
To prove that the global variable is shared between requests. I defined a global variable and increased it’s number every time a new request is received by expressjs.

Then I proved it. The count doesn’t get reset for each request, it keeps increasing. It tell us that node expressjs use the same V8 JavaScript runtime engine instance (thing carefully, it should).

You have to be very careful when a new variable is introduced, don’t forget to declaration word. You may use let, var or const. This article will not discuss the difference between them.

Can you use a global variable as a singleton?

发表评论

您的电子邮箱地址不会被公开。