Note that there are some explanatory texts on larger screens.

plurals
  1. PONode js globals within modules
    primarykey
    data
    text
    <p>In node I see variables initialized global inside modules are getting mixed up [changes done by one request affects the other] across requests. For Ex:</p> <p><strong>a.js</strong></p> <pre><code>var a; function printName(req, res) { //get param `name` from url; a = name; res.end('Hi '+a); } module.exports.printName = printName; </code></pre> <p><strong>index.js</strong></p> <pre><code>//Assume all createServer stuffs are done and following function as a CB to createServer function requestListener(req, res) { var a = require('a'); a.printName(req, res); } </code></pre> <p>As per my assumption, printName function exported from module 'a' is executed everytime a new request hits node and it will have different scope object everytime. </p> <p>So, having something global inside a module wouldn't be affecting them across requests. </p> <p>But I see that isn't the case. Can anyone explain how does node handle module exports of functions in specific [way it handles the scope of the cached module exports object] and how to overcome this shared global variables across requests within a module?</p> <p>Edit [We do async task per request]: With rapid requests in our live system. Which basically query redis and responds the request. We see wrong response mapped to wrong request (reply [stored in a global var in the module] of a redis look up wrongly mapped to diff req). And also we have some default values as global vars which can be overridden based on request params. Which also is getting screwed up</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload