Problem when inserting new element in array

3

Hello, I have the following code:

var fs = require('fs');

function search(text) {
    var response = [];

    fs.readdir('documents',(err, files) => {
        files.forEach(file => {
            if(file.toLowerCase().indexOf(text.toLowerCase()) != -1){
                console.log("Encontrado " + file);
                response.push(file);
            }
        })
    });

    return response;
}

exports.search = search;

What it does is search in a folder all the files that contain in its name ( file ) a certain substring ( text ), the idea is that all the matching files must store their name in the% array response the problem is that when returning the array it appears empty (print [] )

As you can see, I have a console.log to see if there is a match at any moment and to confirm that this happens, now the problem is that it seems that the line of the push will never be executed ...

    
asked by Cristofer Fuentes 03.04.2017 в 06:55
source

1 answer

3

You are doing one of asynchronous functions, and, therefore, when you get to your return , absolutely no line of your filter has been executed , so you return a array empty.

2 options:

1. Use callbacks

function search(text, callback ) {
  var response = [];

  fs.readdir('documents',(err, files) => {
    files.forEach( file => {
      if(file.toLowerCase().indexOf(text.toLowerCase()) != -1){
        console.log("Encontrado " + file);
        response.push(file);
      }
    } )
    callback( response );
  } );
}

2. Use synchronous functions

function search(text) {
  var response = [ ],
      files = fs.readdirSync( 'documents' );

  files.forEach(file => {
    if(file.toLowerCase().indexOf(text.toLowerCase()) != -1){
      console.log("Encontrado " + file);
      response.push(file);
    }
  })

  return response;
}
    
answered by 03.04.2017 / 07:07
source