[英]nodejs import dynamic variable from another file
通過使用module.exports = var;
和const var = require("./file.js");
我們可以從另一個文件訪問一個變量,但是導入的變量是static,即使原始變量在原始文件中發生變化也不能改變,我如何導出一個可以隨時更新並在另一個文件中實時訪問的數組?
將您的變量放在返回變量的 function 中,然后導出 function
export function getVariable(){
let myVar = 0;
return myVar
}
module.exports = getVariable;
const getVar = require('../file.js');
如果您將變量存儲在代碼中的某處,您可以通過它來區分您有興趣閱讀的文件。
您可以使用以下方法使用變量動態更改文件名。
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); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.