0

我将一个变量值从 file1.js 导出到 file2.js,它可以正常工作,但是如果我想从 file1.js 中的 file2.js 更改该变量的值,它就不起作用。这是否适用于只读,如果可以,我如何连接这两个文件,我可以将值从一个文件更改为另一个文件,反之亦然?

更新:如果在 file1.js 我有let count = 0,并且从 file2.js 我想将计数值更改为count = 2,我该如何更改它,因为它不会更改为 file1..

更新 2 - 已解决:

文件1.js

let var1 = 55 ;
    function testFunk(reVar, i){
       console.log(var1, 'file1')
      if( reVar == 'read' ){
        return var1
      } else if( reVar == 'change' ){
        console.log(' change ')
        var1 = var1 + i ;
        return var1
      }
    }


    module.exports = {  testFunk , var1 }

文件2.js

 var file1 = require("./file1.js") ;
let var1 ; 

testFunk1( )
function testFunk1( ){
   setTimeout(() => {
     var1 = file1.testFunk( 'read') ;
     testFunk1( )
    }, 20);
}


 setInterval(() => {
    file1.testFunk('change', 1 ) ;
   console.log(  var1 , 'file1'  ) ;
  }, 1000);

这样我可以从 file1 中读取变量值,更改它们,然后再次读取更改后的值。这是我问的,希望你现在明白了。如果您有任何其他更好的解决方案,请显示它..

4

1 回答 1

0

在 node js 中,你可以通过 process 对象读取和更改其他 js 文件中声明的变量。它的工作方式类似于浏览器中的窗口对象。

让我们看一个下面的例子

文件1.js

module.exports = process.myGlobals = {name: "prince david", age: 45, married: true}

file2.js 我们可以在file2.js中访问file1.js中声明的变量,如下

let globals = require("./file1.js")

console.log(globals) // the output will be {name: "prince david", age: 45, married: true}
console.log(globals.name) // the output will be prince, david
console.log(globals.age) // the output will be, 45
// to change any of the properties which was defined in file1.js, we can do the following

globals.name = "some other name"
console.log(globals.name) // the output will be, some other name
globals = {programmer: true}
console.log(globals) // the output will be {programmer: true}

所有这些都有效,因为当我们导出使用流程对象声明的变量时,我们甚至传递了它的引用,所以如果我们在任何其他文件中更改该变量,它的初始值也会改变

于 2022-02-14T01:58:54.380 回答