【问题标题】:what gets called first when a directory is treated as a function?当目录被视为函数时首先调用什么?
【发布时间】:2014-01-02 03:27:24
【问题描述】:

开源博客项目 Ghost 有一个 index.js 文件,其中只有这段代码。

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

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

ghost();

如果您运行 node index.js,它会启动应用程序。 require语句中的./core其实是一个目录,里面有很多子目录,所以这个index.js文件本质上就是把整个目录(里面有很多函数和文件)作为函数ghost();调用,这就引出了一个问题,当ghost(); 发生时,实际上首先调用的是什么?它会自动在 /core 目录中查找 index.js 文件吗?

比如./core里面,除了一堆其他目录,还有这个index.js这个文件,里面有一个函数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;

所以我的问题是,当有这样的设置时,整个目录都像函数一样被调用

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

    ghost();

node 是否默认在 ./core 中查找 index.js 文件,并且在这种情况下调用 startGhost?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    我的理解是这样的

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

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

    是等价的。换句话说,要求一个目录只是要求该目录中的 index.js 的简写。

    为了处理您问题的第二部分,您的 index.js 导出 一个函数。这意味着当您 require index.js 时,您的变量将包含一个函数,然后您可以调用,在您的情况下使用 ghost()

    重要的是要了解模块不必导出函数,它们也可以导出对象和其他东西。 This post解释得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 2012-05-17
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多