Global variables for node.js standard modules?

前端 未结 6 1447
故里飘歌
故里飘歌 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条回答
  •  庸人自扰
    2020-11-27 13:20

    global.util = require('util');
    

    There's a section about global objects in the node documentation.

    However, globals should be used with care. By adding modules to the global space you reduce testability and encapsulation. But there are cases where using this method is acceptable. For example, I add functions and objects to the global namespace to use within my unit test scripts.

提交回复
热议问题