Reputation: 1145
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.
Upvotes: 1
Views: 111
Reputation: 892
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);
Upvotes: 0
Reputation: 13669
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);
}
Upvotes: 2