[英]NodeJS : what is require modules best practices?
目前我已经按照以下结构创建了一个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
有一个内部缓存( require.cache
),因此将使用相同的内存。
来自文档:
require.cache
模块在需要时缓存在此对象中。 通过从此对象中删除键值,下一个require将重新加载模块。
拥有以下文件:
.
├── 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
从加载require.cache
(其中u.say
设置为"Hello Mars!"
由a.js
)。
要防止从缓存加载,您可以使用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!"
因为文件没有从缓存加载而是从磁盘加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.