NodeJS:什么是需求模块的最佳实践?

目前我已经在下面的结构中创build了一个NodeJS项目:

/(root) ----> controller ----> aController.js ----> model ----> module ----> aModule.js ----> util ----> util.js app.js 

问题是例子,在controller/aController.js我使用模块fs,所以我做fs = require('fs')来包含fs模块。

问题是在module/aModule.js我也想用fs,如果我做另一个fs=require('fs')是否正确与“Node.js的方式”?

与上面相同的问题,我想在模块和控制器都require('util/util.js') 。 这种情况下最好的做法是什么?

只需做很多次(在不同的文件中) var fs = require("fs") (或var myLib = require("path/to/my/lib") )。

require有一个内部caching( require.cache ),所以会使用相同的内存。

从文档:

require.cache

当需要时,模块被caching在这个对象中。 通过从这个对象中删除一个键值,下一个要求将重新加载模块。


有以下文件:

 . ├── a.js ├── b.js └── u.js 

u.js

 this.say = "Hello World!"; 

a.js

 var u = require("./u"); u.say = "Hello Mars!"; // change `say` property value require("./b"); // load b.js file 

b.js

 console.log(require("./u").say); // output `say` property 

输出: "Hello Mars!"为什么? 因为从u.js加载的b.js是从b.js加载的(其中u.sayu.say设置为"Hello Mars!" )。

为防止从caching加载,可以使用delete require.cache[<absolute-path-to-file>]require.cachedelete require.cache[<absolute-path-to-file>] 。 让我们改变b.js内容如下:

  delete require.cache[require.resolve("./u")]; console.log(require("./u").say); // output `say` property 

输出: "Hello World!" 因为文件不是从caching中加载的,而是从磁盘加载的。