JavaScript Node.js:如何重新导入已修改的模块

huangapple go评论95阅读模式
英文:

JavaScript Node.js: how to re-import a module that is modified

问题

我有一个后端,在每次调用时,它会导入一个本地的JSON文件并打印其内容,同时它还会在运行时动态修改JSON文件。然而,我遇到的问题是,每次打印内容时,它总是打印出模块第一次导入时的内容,而不是经过多次动态修改后的内容。为了更好地说明,我的JSON文件如下所示:

{
    "number": 1
}

我的后端代码如下:

app.use('/change', async (req, res) => {
    const num = require('number.json').number;
    console.log(num);
    await modifyJsonFile(
        path.join(__dirname, 'number.json'),
        {
            number: num + 1
        }
    );
    res.end();
}

现在有趣的事情发生了。当我第一次调用它时,它会打印出"1",而JSON文件中的数字会变为"2"。当我第二次调用它时,它仍然打印出"1",即使JSON文件中的属性是"2"。我猜测问题的原因是后端始终在第一次导入时使用了JSON模块。有没有可能的解决方案?特别是重新导入修改后的模块,或者其他的解决方法?谢谢。

英文:

I have a backend where every time it gets called, it imports a local JSON file and prints its content, what it also does at the end is dynamically modifying the JSON file at runtime. However, an issue I seem to encounter is that every time it prints the content, it is always the content at the first time the module was imported, instead of the content after the many times it was dynamically modified. To better illustrate, my JSON looks like the following

{
    "number": 1
}

My backend looks like

app.use('/change', async (req, res) => {
    const num = require('number.json').number;
    console.log(num);
    await modifyJsonFile(
        path.join(__dirname, 'number.json'),
        {
            number: num + 1
        }
    );
    res.end();

}

Now the interesting thing happens. When I call it the first time, it would print "1", and the number in the JSON file changes to "2". When I call it the second time, it would still print "1", even though the property in the JSON file is "2". My guess for the issue is that the backend has always been using the JSON module the first time it was imported. Any possible solutions? especially on re-importing the modified module, or alternative walk-around? Thanks.

答案1

得分: 1

看起来这是由于缓存导致的问题。它会正确更新,但每次尝试访问时,它都会访问缓存而不是更新后的内容。

因此,解决方案类似于在每次导入后添加缓存清除代码,这样下次访问时,它会为您获取最新的内容。

示例代码如下:

app.use('/change', async (req, res) => {
  const filePath = path.join(__dirname, 'number.json'); // 根据实际情况提供路径

  delete require.cache[filePath]; // 在这里清除缓存

  const num = require(filePath).number;
  console.log(num);
  // 其余的代码
});

filePath中,我们需要根据调用位置的不同来提供dirname,因为缓存的工作方式与此有关。

参考:Node文档这里

这应该可以解决问题。

英文:

It looks like it is happening due to cache. It gets updated correctly but every time you try to access it , it accesses the cache rather that the updated one .
So, the solution will be something like adding cache removal code after each import , so that the next time you access it , it gets the latest one for you.
The sample will be like this

app.use('/change', async (req, res) => {
const filePath = path.join(__dirname, 'number.json');// You can give path accordingly 

delete require.cache[filePath]; // Clears the  cache here 

const num = require(filePath).number;
console.log(num);
//Rest of code 

Here in filePath , we have to provide dirname as caching works differently wrt to where we call it , so we provide the path there.

Refer- Node Documentation here

This is supposed to work .

huangapple
  • 本文由 发表于 2023年8月8日 22:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定