简体   繁体   中英

Node.js Global Variables and using Require

Many people have suggested using "modules" that "export" an object, so that you can bring in variables to another file - because once you require a certain file name once, all future calls in other files to require that same file will immediately return the SAME exported object that was given the first time that file was required without reevaluating any code. This allows you to choose by requiring files which variables you want to share between files without using global, which is essential to maintaining state between files or split up code which needs to use the same variables.

My problem is: How can you modify those exported variables - or are they unchangeable - and if they are unchangeable then they are lacking functionality that you can only achieve using global variables... ?

There are no such things as exportable variables. The require function returns a usual Javascript object, and things you call "exported variables" are just properties of that returned object.

Internally, require() maintains a dictionary mapping module identifiers to these objects and guarantees that the same object is returned for the same module identifiers passed to it.

So you can modify those properties how you want. You can even do things like this:

var connect = require('connect')
connect.foo = 42

This code will effectively monkey-patch connect module and add foo "export" to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM