搜索
首页web前端前端问答node require什么意思

node require什么意思

Oct 18, 2022 pm 05:51 PM
nodejsnoderequire函数require()

node中的require是一个函数,该函数接受一个参数,形参名为id,类型是String;require函数可以导入模块、JSON文件、本地文件;其中模块可以通过一个相对路径从“node_modules”、“本地模块”或“JSON文件”中导出,该路径将针对“__dirname”变量或者当前工作目录。

node require什么意思

本教程操作环境:windows7系统、nodejs18.4.0版、Dell G3电脑。

node require什么意思?

Nodejs中的require函数的具体使用方法

说明

本文参考Node官网文档版本为v11.12.0。

本文主要分析了Nodejs中require导入JSON和js文件时得到的结果,同时简单涉及到了Nodejs中模块导出module.exports和exports的用法。

引言

在阅读webpack源码的过程当中,见到如下一行代码:

const version = require("../package.json").version

故引申出对Nodejs中require的学习。

require介绍

在Node.js的文档中,require的相关文档是在Modules目录下,属于Nodejs模块化系统的一部分。

require是一个函数。通过typeof或者Object.prototype.toString.call()可以验证这个结论:

console.log(require) // 输出:Function
console.log(Object.prototype.toString.call(require) // 输出:[object Function]

通过直接打印require,可以发现在require函数下还挂载着若干个静态属性,这些静态属性也可以在Nodejs的官方文档中直接找到相关的说明:

{ [Function: require]
 resolve: { [Function: resolve] paths: [Function: paths] },
 main:
  Module {
   id: '.',
   exports: {},
   parent: null,
   filename: '/Users/bjhl/Documents/webpackSource/index.js',
   loaded: false,
   children: [],
   paths:
   [ '/Users/bjhl/Documents/webpackSource/node_modules',
    '/Users/bjhl/Documents/node_modules',
    '/Users/bjhl/node_modules',
    '/Users/node_modules',
    '/node_modules' ] },
 extensions:
  [Object: null prototype] { '.js': [Function], '.json': [Function], '.node': [Function] },
 cache:
  [Object: null prototype] {
   '/Users/bjhl/Documents/webpackSource/index.js':
   Module {
    id: '.',
    exports: {},
    parent: null,
    filename: '/Users/bjhl/Documents/webpackSource/index.js',
    loaded: false,
    children: [],
    paths: [Array] } } }

require函数静态属性

这里之后再详细补充。

require使用

在官网文档中可以看到如下关于require的说明:

require(id)#  Added in: v0.1.13  id module name or path  Returns: exported module content  Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory.

同时还给出了三种require的使用方法:

// Importing a local module:
const myLocalModule = require('./path/myLocalModule');

// Importing a JSON file:
const jsonData = require('./path/filename.json');

// Importing a module from node_modules or Node.js built-in module:
const crypto = require('crypto');

从以上文档中可以得出以下信息:

  • require接受一个参数,形参名为id,类型是String。

  • require函数return的是模块到处的内容,类型是任意。

  • require函数可以导入模块、JSON文件、本地文件。模块可以通过一个相对路径从node_modules、本地模块、JSON文件中导出,该路径将针对__dirname变量(如果已定义)或者当前工作目录。

require实践

在这里将分类讨论require的实践结论。

require导入JSON

JSON 是一种语法,用来序列化对象、数组、数值、字符串、布尔值和 null 。

在文章的开头就提到了通过require("./package.json")文件来读取package.json文件中的version属性。这里将尝试导入info.json文件并查看相关信息。

文件结构目录如下:

.
├── index.js
└── info.json

将info.json文件的内容修改为:

{
  "name": "myInfo",
  "hasFriend": true,
  "salary": null,
  "version": "v1.0.0",
  "author": {
    "nickname": "Hello Kitty",
    "age": 20,
    "friends": [
      {
        "nickname": "snowy",
        "age": 999
      }
    ]
  }
}

在info.json当中,包含了字符串、布尔值、null、数字、对象和数组。

将index.js的内容修改如下并在当前terminal运行命令 node index.js ,得到如下结果:

const info = require("./info.json")
console.log(Object.prototype.toString.call(info)) // [object Object]
console.log(info.version) // v1.0.0
console.log(info.hasFriend) // true
console.log(info.salary) // null
console.log(info.author.nickname) // Hello Kitty
console.log(info.author.friends) // [ { nickname: 'snowy', age: 999 } ]

可以看到,require导入一个JSON文件的时候,返回了一个对象,Nodejs可以直接访问这个对象里的所有属性,包括String、Boolean、Number、Null、Object、Array。个人猜测这里可能用到了类似于JSON.parse()的方法。

通过这个结论也得出了一种思路,即通过require方法传入JSON文件来读取某些值,如在文章开头中,webpack通过读取package.json文件获取到了version值。

require导入本地js文件

文件结构目录如下:

.
├── index.js
├── module_a.js
└── module_b.js

index.js文件中,分别按顺序导入了module_a和module_b并赋值,然后将这两个变量打印,内容如下:

console.log("*** index.js开始执行 ***")
const module_a = require("./module_a")
const module_b = require("./module_b")
console.log(module_a, "*** 打印module_a ***")
console.log(module_b, "*** 打印module_b ***")
console.log("*** index.js结束执行 ***")

module_a文件中,未指定module.exports或者exports,但是添加了一个异步执行语句setTimeout,内容如下:

console.log("** module_a开始执行 **")
let name = "I'm module_a"
setTimeout(() => {
  console.log(name, "** setTimeout打印a的名字 **")
}, 0)
console.log("** module_a结束执行 **")

module_b文件中,指定了module.exports(也可以换成exports.name,但是不能直接使用exports等于某个对象,因为exports和module.exports其实是指向了一个地址,引用了相同的对象,如果使用exports等于其他的引用类型,则不再指向module.exports,无法改变module.exports里的内容),内容如下:

console.log("** module_b开始执行 **")
let name = "I'm module_b"
console.log(name, "** 打印b的名字 **")
module.exports = {
  name
}
console.log("** module_b结束执行 **")

在当前目录terminal下运行 node index.js 运行得到如下输出:

*** index.js开始执行 ***
** module_a开始执行 **
** module_a结束执行 **
** module_b开始执行 **
I am module_b ** 打印b的名字 **
** module_b结束执行 **
{} '*** 打印module_a ***'
{ name: 'I am module_b' } '*** 打印module_b ***'
*** index.js结束执行 ***
I am module_a ** setTimeout打印a的名字 **

通过以上执行结果可以得出结论:

  • require某个js文件时,如果未通过exports或者module.exports指定导出内容,则require返回的结果是一个空对象;反之可以通过module.export或者给exports属性赋值来导出指定内容。

  • require某个js文件时,该文件会立即sync执行。

require导入模块

我们先选择一个npm包——cors。 进入文件夹,运行一下命令:

npm init -y // 初始化
echo -e "let cors = require(\"cors\")\nconsole.log(cors)" > index.js // 生成index.js文件
npm install cors --save // 安装cors包

文件结构如下(...处省略了其他的模块):

.
├── index.js
├── node_modules
│  ├── cors
│  │  ├── CONTRIBUTING.md
│  │  ├── HISTORY.md
│  │  ├── LICENSE
│  │  ├── README.md
│  │  ├── lib
│  │  │  └── index.js
│  │  └── package.json
│  │  ...
├── package-lock.json
└── package.json

index.js中的内容如下:

let cors = require("cors")
console.log(cors)

运行 node index.js ,得出以下结果:

[Function: middlewareWrapper]

找到node_modules下的cors模块文件夹,观察cros模块中的package.json文件,找到main字段: "main": "./lib/index.js" ,找到main字段指向的文件,发现这是一个IIFE,在IIFE中的代码中添加,console.log("hello cors"),模拟代码结构如下:

(function () {
  'use strict';
  console.log("hello cors"); // 这是手动添加的代码
  ...
  function middlewareWrapper(o) {
    ...
  }
  module.exports = middlewareWrapper;
})()

再次运行 node index.js ,得出以下结果:

hello cors
[Function: middlewareWrapper]

为什么会打印出 hello cors 呢?因为require模块的时候,引入的是该模块package.json文件中main字段指向的文件。而这个js文件会自动执行,跟require引用本地js文件是相同的。

packjson文档

在npm的官方网站中可以找到关于package.json中的main字段定义。

main   The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.   This should be a module ID relative to the root of your package folder   For most modules, it makes the most sense to have a main script and often not much else.

在以上说明中可以得出以下结论:

  • main字段是一个模块ID,是程序的主入口。

  • 当使用require("xxx")的时候,导入的是main字段对应的js文件里的module.exports。

所以require导入模块的时候,是运行的对应模块package.json中main字段指定的文件。

推荐学习:《node视频教程

以上是node require什么意思的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
CSS:使用ID选择器不好吗?CSS:使用ID选择器不好吗?May 13, 2025 am 12:14 AM

使用ID选择器在CSS中并非固有地不好,但应谨慎使用。1)ID选择器适用于唯一元素或JavaScript钩子。2)对于一般样式,应使用类选择器,因为它们更灵活和可维护。通过平衡ID和类的使用,可以实现更robust和efficient的CSS架构。

HTML5:2024年的目标HTML5:2024年的目标May 13, 2025 am 12:13 AM

html5'sgoalsin2024focusonrefinement和optimization,notnewfeatures.1)增强performandemandeffifice throughOptimizedRendering.2)risteccessibilitywithrefinedibilitywithRefineDatientAttributesAndEllements.3)expliencernsandelements.3)explastsecurityConcerns,尤其是withercervion.4)

HTML5试图改进的主要领域是什么?HTML5试图改进的主要领域是什么?May 13, 2025 am 12:12 AM

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供应,2)语义结构,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,简化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)

CSS ID和类:常见错误CSS ID和类:常见错误May 13, 2025 am 12:11 AM

IDsshouldbeusedforJavaScripthooks,whileclassesarebetterforstyling.1)Useclassesforstylingtoallowforeasierreuseandavoidspecificityissues.2)UseIDsforJavaScripthookstouniquelyidentifyelements.3)Avoiddeepnestingtokeepselectorssimpleandimproveperformance.4

课程和ID选择器之间的差异是什么?课程和ID选择器之间的差异是什么?May 12, 2025 am 12:13 AM

classSelectorSareVersAtileAndReusable,whileIdSelectorSareEctorSareEniqueAndspecific.1)useclassSelectors(表示)

CSS IDS vs类:真正的差异CSS IDS vs类:真正的差异May 12, 2025 am 12:10 AM

IDSareuniqueIdentifiersForsingLelements,而LileclassesstyLemultiplelements.1)useidsforuniquelementsand andjavascripthooks.2)useclassesforporporporblesable,flexiblestylestylestylinglingactossmultiplelements。

CSS:如果我只使用课程怎么办?CSS:如果我只使用课程怎么办?May 12, 2025 am 12:09 AM

使用仅类选择器可以提高代码的重用性和可维护性,但需要管理类名和优先级。1.提高重用性和灵活性,2.组合多个类创建复杂样式,3.可能导致冗长类名和优先级问题,4.性能影响微小,5.遵循最佳实践如简洁命名和使用约定。

CSS中的ID和类选择器:初学者指南CSS中的ID和类选择器:初学者指南May 12, 2025 am 12:06 AM

ID和class选择器在CSS中分别用于唯一和多元素的样式设置。1.ID选择器(#)适用于单一元素,如特定导航菜单。2.Class选择器(.)用于多元素,如统一按钮样式。应谨慎使用ID,避免过度特异性,并优先使用class以提高样式复用性和灵活性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用