搜尋
首頁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 nmod ). 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:我可以在同一DOM中使用多個ID嗎?CSS:我可以在同一DOM中使用多個ID嗎?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

HTML5的目的:創建一個更強大,更容易訪問的網絡HTML5的目的:創建一個更強大,更容易訪問的網絡May 14, 2025 am 12:18 AM

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互動,可及可訪問。 1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

HTML5的重要目標:增強網絡開發和用戶體驗HTML5的重要目標:增強網絡開發和用戶體驗May 14, 2025 am 12:18 AM

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒體綜合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityActibility.2)and tagsallowsemlessallowseamelesseamlessallowseamelesseamlesseamelesseamemelessmultimedimeDiaiaembediiaembedplugins.3)。 3)3)

HTML5:安全嗎?HTML5:安全嗎?May 14, 2025 am 12:15 AM

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrenerabilnerabilityLikeClickLickLickLickjAckJackJacking.2)

與較舊的HTML版本相比,HTML5目標與較舊的HTML版本相比,HTML5目標May 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

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)增強performanceandeffipedroptimizedRendering.2)inviveAccessibilitywithRefinedwithRefinedTributesAndEllements.3)explityconcerns,尤其是withercercern.4.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)

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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器