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');
添加回答
舉報