在node.js项目中,index.js的作用是什么? [英] What is index.js used for in node.js projects?

查看:736
本文介绍了在node.js项目中,index.js的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是要求目录中所有文件的好方法( node.js需要文件夹中的所有文件吗?),index.js主要用于什么?

Other than a nice way to require all files in a directory (node.js require all files in a folder?), what is index.js used for mainly?

推荐答案

当您将文件夹传递到Node的require()时,它将检查端点的package.json.如果未定义,它将检查index.js,最后检查index.node(一种c ++扩展格式).因此index.js很可能是需要模块的入口点.

When you pass a folder to Node's require(), it will check for a package.json for an endpoint. If that isn't defined, it checks for index.js, and finally index.node (a c++ extension format). So the index.js is most likely the entry point for requiring a module.

在此处查看官方文档: http://nodejs.org/api/modules.html#modules_folders_as_modules

See the official Docs here: http://nodejs.org/api/modules.html#modules_folders_as_modules.

此外,您询问如何要求目录中的所有文件.通常,您需要一个带有index.js的目录,该目录向这些文件公开一些封装的接口.每个模块执行此操作的方式将有所不同.但是,假设您想在包含文件夹时包含该文件夹的内容(请注意,这不是最佳做法,并且出现的频率比您想象的要少).然后,您可以使用index.js来同步加载目录中的所有文件(异步设置导出通常会询问严重的错误)并将它们附加到module.exports,如下所示:

Also, you ask how to require all the files in a directory. Usually, you require a directory with an index.js that exposes some encapsulated interface to those files; the way to do this will be different for ever module. But suppose you wanted to include a folder's contents when you include the folder (note, this is not a best practice and comes up less often than you would think). Then, you could use an index.js that loads all the files in the directory synchronously (setting exports asynchronously is usually asking for terrible bugs) and attaches them to module.exports like so:

var path = require('path'),
    dir = require('fs').readdirSync(__dirname + path.sep);

dir.forEach(function(filename){

    if(path.extname(filename) === '.js' && filename !== 'index.js'){
        var exportAsName = path.basename(filename);
        module.exports[exportAsName] = require( path.join( __dirname, filename) );
    }

});

尽管如此,我几乎从未见过有人想要使用该模式-大多数时候,您希望index.js像

I hardly ever see people wanting to use that pattern though - most of the time you want your index.js to go something like

var part1 = require('./something-in-the-directory'),
    part2 = require('./something-else');
....
module.exports = myCoolInterfaceThatUsesPart1AndPart2UnderTheHood;

这篇关于在node.js项目中,index.js的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆