gpt4 book ai didi

javascript - Node : what is require modules best practices?

转载 作者:行者123 更新时间:2023-11-30 12:33:58 25 4
gpt4 key购买 nike

目前我已经按照以下结构创建了一个 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 方式”?

与上述问题相同,我也想在模块和 Controller 中都使用 require('util/util.js')。在这种情况下,最佳做法是什么?

最佳答案

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

require有一个内部缓存(require.cache),因此将使用相同的内存。

来自文档:

require.cache

Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module.


例子

具有以下文件:

.
├── 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.jsb.js 加载从 require.cache 加载(其中 u.say"Hello Mars!" 设置为 a.js)。

要防止从缓存中加载,您可以从 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!"因为文件不是从缓存中加载的,而是从磁盘中加载的。

关于javascript - Node : what is require modules best practices?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com