目录作为模块


将程序和库组织到自包含目录中,然后为这些目录提供单个入口点是很方便的。 可以通过三种方式将文件夹作为参数传给 require()

首先是在文件夹的根目录创建 package.json 文件,指定 main 模块。 一个示例 package.json 文件可能如下所示:

{ "name" : "some-library",
  "main" : "./lib/some-library.js" }

如果这是在 ./some-library 的文件夹中,则 require('./some-library') 将尝试加载 ./some-library/lib/some-library.js

这就是 Node.js 中对 package.json 文件的认识程度。

如果目录中不存在 package.json 文件,或者 "main" 条目丢失或无法解析,则 Node.js 将尝试从该目录中加载 index.jsindex.node 文件。 例如,如果前面的示例中没有 package.json 文件,则 require('./some-library') 将尝试加载:

  • ./some-library/index.js
  • ./some-library/index.node

如果这些尝试失败,Node.js 将报告整个模块丢失,并显示默认错误:

Error: Cannot find module 'some-library'

It is convenient to organize programs and libraries into self-contained directories, and then provide a single entry point to those directories. There are three ways in which a folder may be passed to require() as an argument.

The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:

{ "name" : "some-library",
  "main" : "./lib/some-library.js" }

If this was in a folder at ./some-library, then require('./some-library') would attempt to load ./some-library/lib/some-library.js.

This is the extent of the awareness of package.json files within Node.js.

If there is no package.json file present in the directory, or if the "main" entry is missing or cannot be resolved, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the previous example, then require('./some-library') would attempt to load:

  • ./some-library/index.js
  • ./some-library/index.node

If these attempts fail, then Node.js will report the entire module as missing with the default error:

Error: Cannot find module 'some-library'