1

I am using the express module to do some simple variable passing.

The below are my codes

    app.get('/dosomething', function(req, res){ 
          var myText = req.query.mytext; //mytext is the name of your input box
          console.log(myText);

          var googleSent = require("./dosomethingelse");
     }); 

Basically, I have an html form which will send some text to NodeJS on submit. It successfully goes into the NodeJs and I am able to console it out. But I am not able to use the variable within the dosomethingelse.js, I tried to use module.export but I realize this doesn't really fit my case.

So are there s a solution for this or I am not doing it in the right way?

Let's ask this question in another way:

    app.get('/dosomething', function(req, res){ 
        var myText = req.query.mytext; //mytext is the name of your input box
        console.log(myText);

        module.exports.myText = myText;
     });


    app.get('/dosomething2', function(req, res){ 
            console.log(app.mytext)
         });

Let's say I got my result in the first app.get and I want the dosomething2 able to console the same result, I tried the code above but it seems it does not work for me.

Anson Aştepta
  • 1,125
  • 2
  • 14
  • 38
  • Possible duplicate of [What is the purpose of Node.js module.exports and how do you use it?](https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) – Dan O May 24 '18 at 13:59
  • Can you post your dosomethingelse.js file code? – Harshal Yeole May 24 '18 at 14:02

2 Answers2

2

Define global variable and use it in any file

app.get('/dosomething', function(req, res){ 

          global.myText = req.query.mytext;
          console.log(myText);
          var googleSent = require("./dosomethingelse");
}); 

in your dosomethingelse file :

module.exports=function(){
     console.log('from file',global.myText);
}
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
0

You should use a common container. You can use create a container and pass it to dosomethingelse or use a singleton

// singleton.js
class Singleton {

  set myText(value) {
    this._myText = value;
  }

  get myText() {
    return this._myText;
  }
}
module.exports = new Singleton();

In your app

// app.js
const singleton = require('./singleton');
app.get('/dosomething', function(req, res) {
   singleton.myText = req.query.myText;
   // ....
 });
// dosomethingelese.js
const singleton = require('./singleton');
console.log(singleton.myText);
Daniele
  • 842
  • 8
  • 11