通過使用module.exports = var;andconst var = require("./file.js");
我們可以從另一個檔案訪問一個變數,但是匯入的變數是靜態的,即使原始檔案中的原始變數發生變化也不能改變,我如何匯出一個可以隨時更新并實時訪問的陣列另一個檔案?
uj5u.com熱心網友回復:
將變數放在回傳變數的函式中,然后匯出函式
export function getVariable(){
let myVar = 0;
return myVar
}
module.exports = getVariable;
const getVar = require('../file.js');
uj5u.com熱心網友回復:
如果您將變數存盤在代碼中的某個位置,您可以通過它來區分您有興趣閱讀的檔案。
您可以使用以下方法通過變數動態更改檔案名。
const readFile = async() => {
try {
const num = 1;
// your variable which will be used to change the destination file.
let world = await fs.promises.readFile(path.join(__dirname, `data/fileName${num}.json`), "utf8");
world = JSON.parse(world);
console.log(world);
// data you're intrested in!
} catch (err) {
console.log(err);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432972.html
標籤:javascript 节点.js
上一篇:如何使用hive從字串列中提取值
