亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

需要的動態變量

需要的動態變量

炎炎設計 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 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號