简体   繁体   English

nodejs从另一个文件导入动态变量

[英]nodejs import dynamic variable from another file

by using module.exports = var;通过使用module.exports = var; and const var = require("./file.js");const var = require("./file.js"); we can access a variable from another file but the imported variable is static and cannot change even if the original variable changes in the original file, how can I export an array that can be updated at any time and accessible in real time in another file?我们可以从另一个文件访问一个变量,但是导入的变量是static,即使原始变量在原始文件中发生变化也不能改变,我如何导出一个可以随时更新并在另一个文件中实时访问的数组?

put your variable inside of a function that returns the variable then export the function将您的变量放在返回变量的 function 中,然后导出 function

export function getVariable(){
  let myVar = 0;
  return myVar
}
module.exports = getVariable;

const getVar = require('../file.js');

If you are storing the variable somewhere in the code by which you can differentiate between the files that you're interested in reading.如果您将变量存储在代码中的某处,您可以通过它来区分您有兴趣阅读的文件。

You might use the following approach by which you change the file name dynamically with the variable.您可以使用以下方法使用变量动态更改文件名。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM