Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

what gets called first when a directory is treated as a function?

what gets called first when a directory is treated as a function?

Problem

The open source blogging project Ghost has an index.js file with just this code in it.

// # Ghost bootloader
// Orchestrates the loading of Ghost
// When run from command line.

var ghost = require('./core');

ghost();

If you run node index.js, it starts the application. The ./core in the require statement is actually a directory with a lot of sub-directories in it, so this index.js file is essentially calling the whole directory (which has many functions and files in it) as a function ghost();, which begs the question, what is actually being called first when ghost(); happens? Will it automatically look for an index.js file inside the /core directory?

For example, inside ./core, in addition to a bunch of other directories, there's also this index.js file with one function in it startGhost

// # Ghost bootloader
// Orchestrates the loading of Ghost
// When run from command line.

var config             = require('./server/config'),
    errors             = require('./server/errorHandling');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

function startGhost(app) {
    config.load().then(function () {
        var ghost = require('./server');
        ghost(app);
    }).otherwise(errors.logAndThrowError);
}

module.exports = startGhost;

so my question is, when there's a setup like this where a whole directory is called like a function

   var ghost = require('./core');

    ghost();

is node's default to look for an index.js file inside ./core, and, in this case, call startGhost?

Problem courtesy of: BrainLikeADullPencil

Solution

The way I understand it is that

var ghost = require('./core');
ghost();

and

var ghost = require('./core/index.js');
ghost();

are equivalent. In other words, requiring a directory is just short hand for requiring the index.js in that directory.

To deal with the second part of your question, your index.js exports a function. This means that when you require index.js your variable will contain a function with you can then call, in your case with ghost().

It is important to understand that modules don't have to export a function, they can export an object and other things as well. This post explains it well.

Solution courtesy of: Frans

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

what gets called first when a directory is treated as a function?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×