How to return a function from callback?

If I have the following code:

var content;
var f = fs.readFile('./index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
    return console.log(content);
});

f();

I got the following:

f();
^
TypeError: undefined is not a function

How can I do to return a function, which is not undefined?

My real issue, in a bigger context is the following https://gist.github.com/jrm2k6/5962230

You can't usefully return from within the callback to your code.

  1. Using return inside the callback doesn't return a value to your code. fs.readFile() calls the callback itself so the return value is given to it. For your code to receive it, fs.readFile() would have to return the value it got from the callback, which it doesn't.

  2. And, since fs.readFile() is asynchronous, it actually can't. Your code spans 2 different points in time:

    1. "Present"

      var content;
      var f = fs.readFile('./index.html', /* ... */);
      
      f();
      
    2. "Future"

      /* ... */
      function read(err, data) {
          if (err) {
              throw err;
          }
          content = data;
          return console.log(content);
      }
      /* ... */
      

You simply can't use a value from the "Future" in the "Present" -- or, at that point, the "Past."

This all generally leads to continuing the callback pattern rather than using return. Taking your "real" code:

var cheerioURLContent = function (url, callback) {
    rest.get(url).on("complete", function (result) {
        callback(cheerio.load(result));
    });
};

cheerioURLContent('./index.html', function (t) {
    console.log(t);
});

You can assign event handlers for custom events and trigger (emit) the events from within the callback. It's a bit hard to get your head around at first, but pretty elegant.

See Emitting event in Node.js for an example.