为了账号安全,请及时绑定邮箱和手机立即绑定

需要的动态变量

需要的动态变量

炎炎设计 2023-03-24 15:10:53
我怀疑我是否读取了带有“require”的 JSON 文件,并且这个 JSON 文件更新后也会更改代码中设置的变量?这是一个例子——这是不断更新的 json 文件context = {id: 45121521541, //changing valuename: node,status: completed,}我通过这段代码得到了这个 JSON 的值var context = require ('./ context.json')代码会不断更新 json 并且数据会发生变化,当代码处于活动状态时,我将通过“require”获取 JSON 的值,这是可能的,或者 require 不允许我?
查看完整描述

1 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

您应该使用fs.readFileSync()它而不是require()- 当您第一次使用 require 时,它会将其提取到模块 require 缓存中,后续调用将从那里加载,因此您不会看到及时的更新。如果您从中删除密钥,require.cache它也会触发重新加载,但总体而言效率会低于仅读取文件。

includingfs.readFileSync()每次执行时都会同步读取文件内容(阻塞)。您可以结合自己的缓存/等来提高效率。如果您可以异步执行此操作,那么 usingfs.readFile()是更可取的,因为它是非阻塞的。

const fs = require('fs');


// your code


// load the file contents synchronously

const context = JSON.parse(fs.readFileSync('./context.json')); 


// load the file contents asynchronously

fs.readFile('./context.json', (err, data) => {

  if (err) throw new Error(err);

  const context = JSON.parse(data);

});


// load the file contents asynchronously with promises

const context = await new Promise((resolve, reject) => {

  fs.readFile('./context.json', (err, data) => {

    if (err) return reject(err);

    return resolve(JSON.parse(data));

  });

});

如果你想从中删除require.cache你可以这样做。


// delete from require.cache and reload, this is less efficient...

// ...unless you want the caching

delete require.cache['/full/path/to/context.json'];

const context = require('./context.json'); 


查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 70 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信