简体   繁体   中英

Callback confusion fs module

I currently wrote this script to run in node:

console.log('Node starting...');
var fs = require('fs');
fs.readFile('./app.js', function(err, data){
    // if(err) throw err;
    console.log(data.toString());
});

I understand the function being passed to readFile(file, callback(err, data) is a callback function and it will be executed when it receives the data parameter.

My problem is, I am clueless on what is actually passing this function the data?

The documentation states

The callback is passed two arguments (err, data), where data is the contents of the file.

What is actually passing the callback function the arguments?

The fs.readFile function gets the data and then calls the callback function with the data as an argument.

You could write such a function yourself (and, in fact, you'll probably do it a lot as you use Node.js more) like this:

function readFile(filename, callbackFunction) {
  var data;

  // ...do some work to get the data...

  if(somethingBadHappened) {
    callbackFunction("An error occurred!")
    return;
  }

  // success!
  callbackFunction(null, data);
}

And you'd use it just like you do fs.readFile :

function myCallback(err, data) {
  console.log( data.toString() );
}

readFile( './myfile.txt', myCallback );

If you want, you can read the actual source of fs.readFile . It's quite short (but a little more complicated than my example)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM