Creating a simple function related to nodejs.
function templateList(){
var templateList;
fs.readdir('./data',function(err,fileList){
The total number of files in //./data is 3.
templateteList = `<ul>`;
for(var i = 0 ; i < fileList.length ; i++){
templateList += `<li>${i}</li>`;
}
templateList += `</ul>`;
});
return templateList;
}
In the above code, the expected result of templateList is <ul><li>1</li></li>2</li><3</li>></ul>
.
However, the result is <ul></ul>
.
If you know the reason, please answer ㅠ<
node.js javascript
fs.readdir
operates asynchronously.
It's the strength of node...It's also a pain point caused by unfamiliarity.
In the above code, fs.readdir
is asynchronous, so it ends immediately without a return.
In other words, we will return templateList
immediately without waiting synchronously.
Before entering the for statement, check the fileList.length
value with console.log().
If it is 0 or less than 0, execute the following statement without entering the for statement.
The result can also be <ul></ul>
.
I'm telling you this for those of you who are going to have the same problem as me...
It's a very basic problem, I'm ashamed of it.
function templateList(){
var templateList = `<ul>`;
var fileList = fs.readdirSync('./data');
for(var i = 0 ; i < fileList.length ; i++){
templateList += `<li>${i}</li>`;
}
templateList += `</ul>`;
return templateList;
}
926 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
624 GDB gets version error when attempting to debug with the Presense SDK (IDE)
575 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.