Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 当目录作为函数处理时,首先调用什么?_Node.js - Fatal编程技术网

Node.js 当目录作为函数处理时,首先调用什么?

Node.js 当目录作为函数处理时,首先调用什么?,node.js,Node.js,开源博客项目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有一个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吗?

我的理解是

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

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

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

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

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