• 欢迎订阅我的Youtube频道
  • 欢迎加入我的电报群

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

网络技术 fennng 6个月前 (06-11) 191次浏览 0个评论

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?


峰享技术 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Node ExpressJS – Becareful! A global variable will be shared between requests
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址