About javascript / nodejs

Asked 2 years ago, Updated 2 years ago, 38 views

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

2022-09-20 21:57

3 Answers

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.


2022-09-20 21:57

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>.


2022-09-20 21:57

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;

}


2022-09-20 21:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.