【问题标题】:Nodejs module.exports - Change variable value from other js fileNodejs module.exports - 从其他 js 文件更改变量值
【发布时间】:2020-05-02 14:41:03
【问题描述】:

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

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

更新 2 - 已解决:

file1.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 }

file2.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 中读取变量值,更改它们,然后再次读取更改后的值。这是我问的,希望你现在明白了。如果您有任何其他更好的解决方案,请展示它..

【问题讨论】:

  • 请同时发布您有问题的两个文件的代码。
  • 谁能帮忙?
  • 我也没有理解你的问题。你能详细说明一下吗?
  • 更新已解决..如果您有更好的解决方案请回答..

标签: node.js request module.exports


【解决方案1】:

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

让我们看看下面的例子

file1.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}

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

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2023-01-02
    相关资源
    最近更新 更多