1 回答

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
您應(yīng)該使用fs.readFileSync()
它而不是require()
- 當(dāng)您第一次使用 require 時(shí),它會(huì)將其提取到模塊 require 緩存中,后續(xù)調(diào)用將從那里加載,因此您不會(huì)看到及時(shí)的更新。如果您從中刪除密鑰,require.cache
它也會(huì)觸發(fā)重新加載,但總體而言效率會(huì)低于僅讀取文件。
includingfs.readFileSync()
每次執(zhí)行時(shí)都會(huì)同步讀取文件內(nèi)容(阻塞)。您可以結(jié)合自己的緩存/等來提高效率。如果您可以異步執(zhí)行此操作,那么 usingfs.readFile()
是更可取的,因?yàn)樗欠亲枞摹?/p>
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');
添加回答
舉報(bào)