NodeJS require('..')? [英] NodeJS require('..')?

查看:217
本文介绍了NodeJS require('..')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览一些NodeJS示例,并且遇到了以下情况:

I've been looking through some NodeJS examples and I've encountered the following:

var module = require('..');
var module = require('../');

我理解require会做什么,但是当它写成这样的时候我不理解它会做什么.有人可以给我解释一下吗?

I understand what require does, but I don't understand what it does when it's written like this. Can somebody explain it to me please?

推荐答案

这是 https中定义的规则://nodejs.org/api/modules.html

在路径Y处从模块请求(X)

require(X) from module at path Y

  1. 如果X以'./'或'/'或'../'开头
    一种. LOAD_AS_FILE(Y + X)
    b. LOAD_AS_DIRECTORY(Y + X)
  1. If X begins with './' or '/' or '../'
    a. LOAD_AS_FILE(Y + X)
    b. LOAD_AS_DIRECTORY(Y + X)

由于../..不是文件,它将进入路径B,作为目录加载

Since ../ or .. is not a file, it will go to path B, to load as directory

LOAD_AS_DIRECTORY(X)

LOAD_AS_DIRECTORY(X)

  1. 如果X/package.json是文件,
    一种.解析X/package.json,然后查找主要"字段.
    b.让M = X +(json主字段)
    C. LOAD_AS_FILE(M)
  2. 如果X/index.js是文件,则将X/index.js加载为JavaScript文本.停止
  3. 如果X/index.json是文件,则将X/index.json解析为JavaScript对象.停止
  4. 如果X/index.node是文件,则将X/index.node加载为二进制插件.停止
  1. If X/package.json is a file,
    a. Parse X/package.json, and look for "main" field.
    b. let M = X + (json main field)
    c. LOAD_AS_FILE(M)
  2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
  3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
  4. If X/index.node is a file, load X/index.node as binary addon. STOP

根据该规则,它将按此顺序检查以下文件

By that rule, it will check the following files in this order

1)../package.json

2)../index.js

3)../index.json

4)../index.node

这篇关于NodeJS require('..')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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