Consider the following simple script:
var sourcePath = 'src';
function setPath(path){
sourcePath = path || sourcePath;
return sourcePath;
}
console.log('sourcePath is ' + setPath('somepath') + ' from setPath.js calling the function');
console.log('sourcePath is ' + sourcePath + ' from setPath.js sourcePath vaue ');
exports.getCustomContextPath = setPath;
exports.sourcePath = sourcePath;
The output of running this script is as expected, when it is run:
sourcePath is somepath from setPath.js calling the function
sourcePath is somepath from setPath.js sourcePath value
If I import the same file in a tester file and use it like so:
const pathSetter = require('./setPath');
var test = pathSetter.getCustomContextPath('./temp/test');
console.log('the path set from test.js ' + test + " by calling getCustomContextPath function with '.temp/test'" )
console.log('the path set from test.js ' + pathSetter.sourcePath + " this is the sourcePath value after calling with '.temp/tr'" )
var test2 = pathSetter.getCustomContextPath();
console.log('the path set from test.js' + test2 + " by calling getCustomContextPath function with no parameter " )
console.log('the path set from test.js ' + pathSetter.sourcePath + " this is the sourcePath value after calling with no parameter")
I expect the value of sourcePath
variable to be changed when setPath
function is called but as you see below, when printing out the value of sourcePath
, it is still set to its default value somePath
. Here is the output of running the test script:
sourcePath is somepath from setPath.js calling the function
sourcePath is somepath from setPath.js sourcePath value
the path set from test.js ./temp/test by calling getCustomContextPath function with '.temp/test'
the path set from test.js somepath this is the sourcePath value after calling with '.temp/tr'
the path set from test.js./temp/test by calling getCustomContextPath function with no parameters
the path set from test.js somepath this is the sourcePath value after calling with no parameters
Can anyone tell me why the value of sourcePath
is not changed after I expected the script function to change it, but only when I directory access it from the test file as oppose to when the function call returns it?