Inject a global variable into node context

61 views
Skip to first unread message

Chen Yang

unread,
May 29, 2018, 9:00:07 AM5/29/18
to nodejs

Could i inject a global variable into node context, like "document" in html's script, which any javascript files could access this variable, and it isn't needed to import or require it?

//var document = require('document') // i don't need to require it by myself
document.findById('111')

Mikkel Wilson

unread,
May 29, 2018, 9:06:44 PM5/29/18
to nodejs

You can use process.env much the way you describe, but this really isn't recommended. Using a global context will make your code very difficult to test. Think in smaller units and compose more complex things from them.

HTH,
Mikkel

Zlatko

unread,
May 30, 2018, 9:44:45 AM5/30/18
to nodejs
You could use the `global` object (https://nodejs.org/api/globals.html#globals_global) the same way you use `window` In the browser. But like in the browser, it's not recommended, in fact for most use cases it is actually discouraged.

But if you tell us why you need it, perhaps we can find a better pattern for you?

kai zhu

unread,
May 30, 2018, 9:45:13 AM5/30/18
to nod...@googlegroups.com

i would disagree about global-variables being bad-practice.  they are oftentimes more elegant and simpler in solving a web-project's integration-level problems (as long as you pick long-enough names that are unique), than some of the contortionist, module-loading hacks i've seen which try to avoid it.

-kai


--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+unsubscribe@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/5bdc3bac-3eb5-4b4a-9618-35217890ee87%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

kai zhu

unread,
May 30, 2018, 12:45:01 PM5/30/18
to nod...@googlegroups.com
this discouragement of global/window variables is honestly nonsense that makes web-project integration/qa work needlessly more complicated and error-prone than needs be.  for example, here’s a simple frontend interview-question that can tell you if the applicant can quickly get integration-level tasks done (using global variables), or tries to over-engineer something overly complicated and hard-to-integrate instead.

frontend interview-question: how would you implement some simple and reusable, frontend-code so that pressing ctrl-a / cmd-a inside a <pre> element will only select-all text inside that element (and not the entire document)?

correct, simple and reusable frontend-solution using global variable window.domOnEventSelectAllWithinPre:
```html
<script>
// init domOnEventSelectAllWithinPre
(function () {
/*
 * this function will limit select-all within <pre tabIndex="0"> elements
 * you can copy-paste this reusable code into pretty much any webpage and it will work
 */
    "use strict";
    // prevent this code from running more than once, if duplicated in scripts/rollups
    if (window.domOnEventSelectAllWithinPre) {
        return;
    }
    window.domOnEventSelectAllWithinPre = function (event) {
        var range, selection;
        if (event &&
                event.code === "KeyA" &&
                (event.ctrlKey || event.metaKey) &&
                event.target.closest("pre")) {
            range = document.createRange();
            range.selectNodeContents(event.target.closest("pre"));
            selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            event.preventDefault();
        }
    };
    // init event-handling
    document.addEventListener("keydown", window.domOnEventSelectAllWithinPre);
}());
</script>

<label>press ctrl-a in the &lt;pre&gt; element below to only select-all text inside it</label><br>
<pre style="border:1px solid black" tabIndex="0">
hello
world!
</pre>
```


On 30 May 2018, at 1:11 PM, Zlatko <zlad...@gmail.com> wrote:

You could use the `global` object (https://nodejs.org/api/globals.html#globals_global) the same way you use `window` In the browser. But like in the browser, it's not recommended, in fact for most use cases it is actually discouraged.

But if you tell us why you need it, perhaps we can find a better pattern for you?

--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.

To post to this group, send email to nod...@googlegroups.com.

Zlatko Đurić

unread,
May 31, 2018, 3:49:52 AM5/31/18
to nod...@googlegroups.com
I would partially agree that if you know JavaScript enough, using global isn't a problem per se. Just like using eval shouldn't cause trouble, if you know what you're doing.

But both are still discouraged for certain reasons. Somewhat simplified example of namespace mess is the recent Array.prototype.smoosh mess. It's not a big deal, but since someone "polluted" a built-in Array prototype by monkey-patching it, now the method name will be "flat" instead of flatten. Again, not a big deal, just slightly inconsistent with other methods on that prototype.

Much more chaos was the era before "modern" JavaScript, frameworks and approaches to client side scripting. I've personally scratched my head on more than one occasion because of name collisions like that , and I didn't really did that much JavaScript at the time. No big deal and eventually I've figured it out. I'm just saying that if it was namespaced, I would avoid that little bump.

So I'm not saying "never do it, it's bad, you're an idiot if you use globals and the devil will get you". I'm just saying that _generally_ speaking it's not recommended if there are clear and simple ways that do not use globals.

Your example shows a good use case and a reasonably unique name for the `global` property. But if the original poster is even asking such a question, he might be just a bit inexperienced. And  he's going to go bug fixing some  senior devs code. And he is going to name his global`next` and  nobody is going to see it coming when he overwrites some other function's optional callback and their API starts crashing _sometimes_.

Obviously he should know better and ideally he'd have tests catch this. But not always and in most cases you really don't need a global so you can do without having to hunt down for such a bug.

So while I agree with you that it's not always an antipattern, I'd say that the OK should avoid this if they can. Most likely they have a perfectly good solution without using global until they learn better and know when and how to use globals "safely".

It's what I think, at least, don't take my words for a rule.



You received this message because you are subscribed to a topic in the Google Groups "nodejs" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/nodejs/i_ALAnVa5xA/unsubscribe.
To unsubscribe from this group and all its topics, send an email to nodejs+un...@googlegroups.com.

To post to this group, send email to nod...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.
--
Zlatko
Reply all
Reply to author
Forward
0 new messages