简体   繁体   English

node.js中的require(../)如何工作?

[英]How does require(../) in node.js work?

What modules does node.js look for when it encounters var foo=require(../) ? node.js在遇到var foo = require(../)时会查找哪些模块?

It would seem that it would look in the directory one UP from the current one, but what exactly would it look for and do? 它似乎会从目前的目录中查找一个UP,但它究竟会寻找和做什么?

Perhaps there is an analogy with include in C or import in Python? 也许在C中包含include或在Python中导入有类比?

I've been starting with node.js and reading http://nodejs.org/api/modules.html and came upon example code on github such as 我一直在开始使用node.js并阅读http://nodejs.org/api/modules.html并在github上找到示例代码,例如

var express = require('express')
  , tracker = require('../')

This code would seem to assign variable express contents of express module (file) whose path must be global after using npm to install express, that much seems understandable,although I understand there are two types of module installation, but that is another question. 使用npm安装express后,这段代码似乎分配了快速模块(文件)的变量快速内容,其路径必须是全局的,这看起来很容易理解,虽然我知道有两种类型的模块安装,但这是另一个问题。

But what contents are assigned to variable tracker ? 但是什么内容被分配给变量跟踪器

This depends on WHAT is in that directory. 这取决于该目录中的内容。

If X begins with './' or '/' or '../' : 如果X以'./'或'/'或'../'开头

a. 一种。 LOAD_AS_FILE(Y + X) LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X) LOAD_AS_DIRECTORY(Y + X)

LOAD_AS_FILE(X): LOAD_AS_FILE(X):

  1. If X is a file, load X as JavaScript text. 如果X是文件,则将X加载为JavaScript文本。 STOP
  2. If X.js is a file, load X.js as JavaScript text. 如果X.js是文件,请将X.js作为JavaScript文本加载。 STOP
  3. If X.node is a file, load X.node as binary addon. 如果X.node是一个文件,则将X.node加载为二进制插件。 STOP

LOAD_AS_DIRECTORY(X): LOAD_AS_DIRECTORY(X):

  1. If X/package.json is a file, 如果X / package.json是一个文件,
    a. 一种。 Parse X/package.json, and look for "main" field. 解析X / package.json,并查找“main”字段。
    b. let M = X + (json main field) 设M = X +(json主场)
    c. C。 LOAD_AS_FILE(M) LOAD_AS_FILE(M)
  2. If X/index.js is a file, load X/index.js as JavaScript text. 如果X / index.js是文件,则将X / index.js加载为JavaScript文本。 STOP
  3. If X/index.node is a file, load X/index.node as binary addon. 如果X / index.node是文件,则将X / index.node加载为二进制插件。 STOP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM