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