-1

My questions here is about the way the call back function works.

const fs = require('fs');

let fileContents = 'initial value';
fs.readFile('file.txt', 'utf-8',function(error,res){
    fileContents = res;
    console.log(fileContents);
})

So, when the fs.readFile runs, the function(error,res) is called. But why does the fileContents receives the text inside the txt file if my parameter is empty? I'm assuming that the readFile adds the value read to the res parameter. Is it always like this?

Another questions is why do I get null when I erase error?

will
  • 31
  • 5
  • It expects a function with those two parameters as the callback for readFile() – Ryan Wilson Jun 04 '18 at 14:13
  • What do you mean by “my parameter is empty”? _You_ don’t provide those arguments, the API does. `error` is the first positional parameter. You can’t simply remove it. – Sebastian Simon Jun 04 '18 at 14:16
  • Possible duplicate of [Where do the parameters in a javascript callback function come from?](https://stackoverflow.com/questions/34624634/where-do-the-parameters-in-a-javascript-callback-function-come-from) – Sebastian Simon Jun 04 '18 at 14:18

2 Answers2

2

Readfile looks like something like this:

 function readFile(path, cb) {
   try {
   // Some very complicated stuff
   // All fine, call callback:
   path(/*error:*/ null, /*res: */ "somedata");
  } catch(error) {
   path(error, /*res: */ undefined);
 }
}

So what you get inside the callbacks parameter does not depend on its name, but on its position, so when you do:

readFile("/..", function(res) { /*...*/ });

res will be the error readFile passes back, and if thats null its a good thing.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

Maybe take a little time to experiment with callback functions.

A callback function is just a function that you pass as a parameter to another function. In the code below I declared my function. myFunc uses another function as parameter to the function called callback. Inside my function I invoke the function and pass myName as parameter to the callback. This allows me to declare other anonymous functions as parameters which I included as examples. When myFunc is invoked it invokes the callback inside its local environment.

I can then manipulate the data that is passed to the callback and write my own code inside the anonymous function using the variable that is passed to myFuncs callback.

In your example you are using readFile which retrieves the data from the file and passes it to a callback function and/or passes an error assuming something went wrong.

function myFunc( callback){
    let myName = "Joe Smo";
    callback(myName);
}
/*
Now I can use my function and add another anonymous function to do whatever I want
provided I use the same parameters that are inside my function. 
*/
myFunc(function(name){
    console.log("What's up!"+name);
});

myFunc(function(strangeName){
    console.log(strangeName+" is a strange name.");

});
MicahB
  • 134
  • 7