Reputation: 283
I am trying to get a specified folder name which has a varied version number suffix with NodeJS like this:
this.getUeeFolderName = function(path)
{
var fileLists = fs.readdirSync(path);
for(var i =0 , l = fileLists.length; i < l ; i++)
{
fileName = fileLists[i];
state = fs.statSync(path+"/"+fileName);
if(state.isDirectory())
{
if(fileName.indexOf('appmw-uee-frontend-') >= 0)
{
return fileName;
}
}
}
};
But it sometimes returns "undefined", sometimes returns expected string.
Note:This folder cannot be empty since it is a tomcat working directory, my project is always running in tomcat.
Upvotes: 0
Views: 657
Reputation: 70163
If path
is an empty directory, fs.readdirSync(path)
will return an empty array ([]
).
In that case, the for
loop will run zero times. A function that runs that for
loop as its last step will return undefined
in that case. (The return
statement inside the for
loop is never executed in that case.)
So this could be happening when path
is an empty directory.
Another possibility, though, is that the if
condition is never satisfied. This will also cause the return
statement to be skipped. So, if there is no directory within path
that contains appmw-uee-frontend-
as part of the name, then the function will also return undefined
.
One last possibility: There is a race condition in the code. The directory may exist when fs.readdirSync()
is run, but then may be removed or renamed (by another process) before fs.statSync()
is called on it. In that case, it is not returned, and you get undefined
. Especially if there are a large number of entries to loop through, that may be what's going on too (although I'd recommend confirming the other possibilities aren't what's happening first).
Upvotes: 1
Reputation: 2547
Use forEach()
method rather using a for loop. It will solve your issue:
Snippet:
this.getUeeFolderName = function(path)
{
var fileLists = fs.readdirSync(path);
fileLists.forEach(fileName,i)
{
state = fs.statSync(path+"/"+fileName);
if(state.isDirectory())
{
if(fileName.indexOf('appmw-uee-frontend-') >= 0)
{
return fileName;
}
}
}
};
Upvotes: 0