带有require的动态变量



如果我读到一个带有"要求";并且这个JSON文件被更新也会更改代码中设置的变量?

这是一个例子-这是不断更新的json文件

context = {
id: 45121521541, //changing value
name: node,
status: completed,
}

我通过这个代码得到这个JSON的值

var context = require ('./ context.json')

代码会不断更新json,数据会发生变化,当代码处于活动状态时,我会通过"require"获取json的值,这是可能的,还是require不允许我?

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

包括fs.readFileSync()将在每次执行时同步读取文件内容(阻塞(。您可以将其与自己的缓存等相结合,以提高效率。如果您可以异步执行此操作,那么最好使用fs.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'); 

最新更新