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.say
被u.say
设置为"Hello Mars!"
)。
为防止从caching加载,可以使用delete require.cache[<absolute-path-to-file>]
从require.cache
中delete 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中加载的,而是从磁盘加载的。