Global variables for node.js standard modules?

前端 未结 6 1441
故里飘歌
故里飘歌 2020-11-27 12:51

I know that global variables are bad.

But if I am using node\'s module \"util\" in 40 files in my framework, isn\'t it better to just declare it as a global variable

6条回答
  •  萌比男神i
    2020-11-27 13:12

    I'm confused by the answers in this thread.

    I am able to do this...

    File: test.js

    global.mytest = {
        x: 3,
        y: function() { console.log('Works.'); }
    };
    

    File: test2.js

    console.log('Does this work?');
    mytest.y();
    

    File: server.js

    require('test.js');
    require('test2.js');
    

    And it seems to work as the question needed. The first require places the mytest object into the global scope, then the second require can access that object without any other qualifiers.

    I was trying to figure this out (which brought me to this thread from a Google search) and I wanted to post what seems to work for me now. Maybe things have changed since the original answers.

提交回复
热议问题