does not return the function read file nodejs

1

the read file function does not return anything, but if it shows by console

function leer(archivo){ 
    fs.readFile('./archivos/'+archivo, 'utf8',
        function(err, data) {

                return data;  
        }
    ); 
};

when I use it from another file

console.log(escritorLector.leer(files[a])); 

shows nothing

However, by console it looks good (in the same file).

function leer(archivo){ 
    fs.readFile('./archivos/'+archivo, 'utf8',
        function(err, data) {
            console.log(data);
            return data;  
        }
    );
};
    
asked by hubman 07.10.2016 в 02:33
source

1 answer

3

You will never get an answer because you are returning from the callback.

You have two options:

  • Pass a callback to leer .
  • Use fs#readFileSync .
  • Passing a callback

    function leer(path, cb) {
      fs.readFile('/archivos/${archivo}', function(err, content) {
        if(err) { /* hacer algo */ }
        cb(content);
      });
    }
    

    And you would use it like this:

    leer('archivo.dat', function(content) {
      console.log(content);
    });
    

    Use fs # readFileSync

    function leer(path) {
      return fs.readFileSync('/archivos/${path}');
    }
    

    And this way if it works what you want:

    console.log(leer('archivo.dat'));
    
        
    answered by 07.10.2016 / 05:20
    source