reset password
Author Message
venny
Posts: 61
Posted 13:41 Oct 20, 2016 |

*Discovered what was going on and got it working*

So I'm trying to do the read and get text function, but whenever I try to do a console.log  ( console.log(readAndTell("graffiti.txt")); )  I keep getting an undefined.  
 

Above it, I have my readfile typed out like in the slides, but wrapped in a function with the file name as the parameter and I return the text within the function(error,text){} parameter.  I get the text within that parameter function, but I can't bring it out to the outer function to return it to the console.log to output it. I just returned the fs.readFile, but it doesn't work.


I would like to copy and paste my code, but I'm unsure if it's considered cheating. 

Why do I keep getting 'undefined' when I call console.log(readAndTell("graffiti.txt")); 

Last edited by venny at 14:04 Oct 20, 2016.
venny
Posts: 61
Posted 13:45 Oct 20, 2016 |

Basically I'm taking this code from the slides:

fs.readFile("file.txt","utf8", function(error,text)){
    if(error)
        throw error;
    console.log("The file contained:", text);
}

and instead it's returning text and it's wrapped in a function returning fs.readFile;

wveit
Posts: 18
Posted 13:13 Oct 21, 2016 |

Hi. I'm not 100% sure about this, but it seems like the fs.readFile function ignores the return value from the callback function you passed to it. The documentation here doesn't mention anything about using returned values from the callback function. fs.readFile is not expecting anything to be returned by that function. Therefore the data your callback is returning (the string) gets lost and nothing happens with it.

The example code works because it does not try to return anything... It processes the string right there in the callback function.

I would look into using fs.readFileSync instead. It is more straight forward to use.

Good luck

Last edited by wveit at 13:15 Oct 21, 2016.
willielf
Posts: 23
Posted 13:31 Oct 21, 2016 |

How did you get it to work? I ran into the same problem too.

 

edit: nvm, the person above me is right.

Last edited by willielf at 13:41 Oct 21, 2016.