
Question:
In my file functions.js i have two functions:
var email, url1
function getFile(_callback){
email = fs.readFileSync("C:/Emails/" + items[2])
_callback(email);
}
function getUrl(){
getLatestMail(function(email) {
email.split(/\n/).forEach(function(line) {
i++;
if (i == 52) {
var test = new Buffer(line, 'base64').toString();
var regex = /=(.+?)"/g
var result1 = regex.exec(test);
url1 = result1[1].toString();
console.log(url1);
}
});
getUrl()
exports.resetUrl = url1;
And i have a file test.js
var Functions = require('../pageobjects/functions.js');
var test = Functions.resetUrl;
console.log(test);
But it returns always undefined! The console.log in getUrl() shows the good value. It looks like that the export not is waiting until the function getURl is loaded. What is the best way to solve this? In this example i removed all the unnecessary code parts.
Answer1:I think that the export of functions.js
should be exports.resetUrl = url1
<strong>EDIT</strong>
You must try another approach because getUrl
method performs asynchronous operation, so before the url1
is set, you do the exports.resetUrl = url1
, so it always will be undefined.
I suggest you to add some callback
parameter to getUrl
function that can be used in test.js
file in order to get access to url1
value
function getUrl(callback){
getLatestMail(function(email) {
email.split(/\n/).forEach(function(line) {
i++;
if (i == 52) {
var test = new Buffer(line, 'base64').toString();
var regex = /=(.+?)"/g
var result1 = regex.exec(test);
url1 = result1[1].toString();
console.log(url1);
// and here use the callback
callback(url1);
}
});
});
exports.resetUrl = getUrl;
Then you could do in test.js
var Functions = require('../pageobjects/functions.js');
Functions.resetUrl(function(url1){
console.log(url1);
});
This is only one option that first came to my mind. I hope that you get the point and understand why url1
in your case was undefined all the time.