gpt4 book ai didi

javascript - 在没有缓存/持久性的情况下执行 nodejs 的最佳方法是什么

转载 作者:行者123 更新时间:2023-11-30 11:18:08 24 4
gpt4 key购买 nike

我正在尝试创建一个 require,它对于每个 require 用途都是唯一的,文件 1、2、300 等都有一个名为 test.js 的文件的 require say。然后可以在一个文件中禁用它,但它的变量在其他文件中保持不变。

文件1.js

const test = require("./test.js");// NOTE enabled boolean in test is default = truetest.enabled = false; // or test.disable();test.sayHello(); // will output nothing as enabled = false

文件2.js

const test = require("./test.js");test.sayHello(); // Should output hello but it as file1 set enabled to false it dosnt

实现此功能的 test.js 是什么样的?

我目前必须通过 module.exports 函数中的参数来执行此操作,这并不理想。例如禁用将测试函数的直接返回,然后是启用/禁用的第二个可选参数。这是嗯...

谢谢

D

最佳答案

即使你可以clear require 缓存,我认为,对于您的特定情况,这是一种不好的做法。

相反,您的 require 调用应该返回一个 class,然后您将在每个文件上使用该类的一个新实例,并在需要时禁用/启用该实例。

test.js

class Test {

disable() {
this.disable = true;
}

sayHello() {
if(this.disable)
return false;

console.log('hello')
}

}

module.exports = Test;

index.js

const Test = require('./test.js');
const test = new Test();
test.disable();
test.sayHello(); // nothing is printed

const otherTest = new Test();
otherTest.sayHello(); // 'hello'

关于javascript - 在没有缓存/持久性的情况下执行 nodejs 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50784556/

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