站長(zhǎng)資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        node require什么意思

        node中的require是一個(gè)函數(shù),該函數(shù)接受一個(gè)參數(shù),形參名為id,類型是String;require函數(shù)可以導(dǎo)入模塊、JSON文件、本地文件;其中模塊可以通過一個(gè)相對(duì)路徑從“node_modules”、“本地模塊”或“JSON文件”中導(dǎo)出,該路徑將針對(duì)“__dirname”變量或者當(dāng)前工作目錄。

        node require什么意思

        node.js極速入門課程:進(jìn)入學(xué)習(xí)

        本教程操作環(huán)境:windows7系統(tǒng)、nodejs18.4.0版、Dell G3電腦。

        node require什么意思?

        Nodejs中的require函數(shù)的具體使用方法

        說明

        本文參考Node官網(wǎng)文檔版本為v11.12.0。

        本文主要分析了Nodejs中require導(dǎo)入JSON和js文件時(shí)得到的結(jié)果,同時(shí)簡(jiǎn)單涉及到了Nodejs中模塊導(dǎo)出module.exports和exports的用法。

        引言

        在閱讀webpack源碼的過程當(dāng)中,見到如下一行代碼:

        const version = require("../package.json").version
        登錄后復(fù)制

        故引申出對(duì)Nodejs中require的學(xué)習(xí)。

        require介紹

        在Node.js的文檔中,require的相關(guān)文檔是在Modules目錄下,屬于Nodejs模塊化系統(tǒng)的一部分。

        require是一個(gè)函數(shù)。通過typeof或者Object.prototype.toString.call()可以驗(yàn)證這個(gè)結(jié)論:

        console.log(require) // 輸出:Function console.log(Object.prototype.toString.call(require) // 輸出:[object Function]
        登錄后復(fù)制

        通過直接打印require,可以發(fā)現(xiàn)在require函數(shù)下還掛載著若干個(gè)靜態(tài)屬性,這些靜態(tài)屬性也可以在Nodejs的官方文檔中直接找到相關(guān)的說明:

        { [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] } } }
        登錄后復(fù)制

        require函數(shù)靜態(tài)屬性

        這里之后再詳細(xì)補(bǔ)充。

        require使用

        在官網(wǎng)文檔中可以看到如下關(guān)于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.

        同時(shí)還給出了三種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');
        登錄后復(fù)制

        從以上文檔中可以得出以下信息:

        • require接受一個(gè)參數(shù),形參名為id,類型是String。

        • require函數(shù)return的是模塊到處的內(nèi)容,類型是任意。

        • require函數(shù)可以導(dǎo)入模塊、JSON文件、本地文件。模塊可以通過一個(gè)相對(duì)路徑從node_modules、本地模塊、JSON文件中導(dǎo)出,該路徑將針對(duì)__dirname變量(如果已定義)或者當(dāng)前工作目錄。

        require實(shí)踐

        在這里將分類討論require的實(shí)踐結(jié)論。

        require導(dǎo)入JSON

        JSON 是一種語法,用來序列化對(duì)象、數(shù)組、數(shù)值、字符串、布爾值和 null 。

        在文章的開頭就提到了通過require("./package.json")文件來讀取package.json文件中的version屬性。這里將嘗試導(dǎo)入info.json文件并查看相關(guān)信息。

        文件結(jié)構(gòu)目錄如下:

        . ├── index.js └── info.json
        登錄后復(fù)制

        將info.json文件的內(nèi)容修改為:

        {   "name": "myInfo",   "hasFriend": true,   "salary": null,   "version": "v1.0.0",   "author": {     "nickname": "Hello Kitty",     "age": 20,     "friends": [       {         "nickname": "snowy",         "age": 999       }     ]   } }
        登錄后復(fù)制

        在info.json當(dāng)中,包含了字符串、布爾值、null、數(shù)字、對(duì)象和數(shù)組。

        將index.js的內(nèi)容修改如下并在當(dāng)前terminal運(yùn)行命令 node index.js ,得到如下結(jié)果:

        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 } ]
        登錄后復(fù)制

        可以看到,require導(dǎo)入一個(gè)JSON文件的時(shí)候,返回了一個(gè)對(duì)象,Nodejs可以直接訪問這個(gè)對(duì)象里的所有屬性,包括String、Boolean、Number、Null、Object、Array。個(gè)人猜測(cè)這里可能用到了類似于JSON.parse()的方法。

        通過這個(gè)結(jié)論也得出了一種思路,即通過require方法傳入JSON文件來讀取某些值,如在文章開頭中,webpack通過讀取package.json文件獲取到了version值。

        require導(dǎo)入本地js文件

        文件結(jié)構(gòu)目錄如下:

        . ├── index.js ├── module_a.js └── module_b.js
        登錄后復(fù)制

        index.js文件中,分別按順序?qū)肓薽odule_a和module_b并賦值,然后將這兩個(gè)變量打印,內(nèi)容如下:

        console.log("*** index.js開始執(zhí)行 ***") 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結(jié)束執(zhí)行 ***")
        登錄后復(fù)制

        module_a文件中,未指定module.exports或者exports,但是添加了一個(gè)異步執(zhí)行語句setTimeout,內(nèi)容如下:

        console.log("** module_a開始執(zhí)行 **") let name = "I'm module_a" setTimeout(() => {   console.log(name, "** setTimeout打印a的名字 **") }, 0) console.log("** module_a結(jié)束執(zhí)行 **")
        登錄后復(fù)制

        module_b文件中,指定了module.exports(也可以換成exports.name,但是不能直接使用exports等于某個(gè)對(duì)象,因?yàn)閑xports和module.exports其實(shí)是指向了一個(gè)地址,引用了相同的對(duì)象,如果使用exports等于其他的引用類型,則不再指向module.exports,無法改變module.exports里的內(nèi)容),內(nèi)容如下:

        console.log("** module_b開始執(zhí)行 **") let name = "I'm module_b" console.log(name, "** 打印b的名字 **") module.exports = {   name } console.log("** module_b結(jié)束執(zhí)行 **")
        登錄后復(fù)制

        在當(dāng)前目錄terminal下運(yùn)行 node index.js 運(yùn)行得到如下輸出:

        *** index.js開始執(zhí)行 ***
        ** module_a開始執(zhí)行 **
        ** module_a結(jié)束執(zhí)行 **
        ** module_b開始執(zhí)行 **
        I am module_b ** 打印b的名字 **
        ** module_b結(jié)束執(zhí)行 **
        {} '*** 打印module_a ***'
        { name: 'I am module_b' } '*** 打印module_b ***'
        *** index.js結(jié)束執(zhí)行 ***
        I am module_a ** setTimeout打印a的名字 **

        通過以上執(zhí)行結(jié)果可以得出結(jié)論:

        • require某個(gè)js文件時(shí),如果未通過exports或者module.exports指定導(dǎo)出內(nèi)容,則require返回的結(jié)果是一個(gè)空對(duì)象;反之可以通過module.export或者給exports屬性賦值來導(dǎo)出指定內(nèi)容。

        • require某個(gè)js文件時(shí),該文件會(huì)立即sync執(zhí)行。

        require導(dǎo)入模塊

        我們先選擇一個(gè)npm包——cors。 進(jìn)入文件夾,運(yùn)行一下命令:

        npm init -y // 初始化 echo -e "let cors = require("cors")nconsole.log(cors)" > index.js // 生成index.js文件 npm install cors --save // 安裝cors包
        登錄后復(fù)制

        文件結(jié)構(gòu)如下(…處省略了其他的模塊):

        . ├── index.js ├── node_modules │  ├── cors │  │  ├── CONTRIBUTING.md │  │  ├── HISTORY.md │  │  ├── LICENSE │  │  ├── README.md │  │  ├── lib │  │  │  └── index.js │  │  └── package.json │  │  ... ├── package-lock.json └── package.json
        登錄后復(fù)制

        index.js中的內(nèi)容如下:

        let cors = require("cors") console.log(cors)
        登錄后復(fù)制

        運(yùn)行 node index.js ,得出以下結(jié)果:

        [Function: middlewareWrapper]

        找到node_modules下的cors模塊文件夾,觀察cros模塊中的package.json文件,找到main字段: "main": "./lib/index.js" ,找到main字段指向的文件,發(fā)現(xiàn)這是一個(gè)IIFE,在IIFE中的代碼中添加,console.log("hello cors"),模擬代碼結(jié)構(gòu)如下:

        (function () {   'use strict';   console.log("hello cors"); // 這是手動(dòng)添加的代碼   ...   function middlewareWrapper(o) {     ...   }   module.exports = middlewareWrapper; })()
        登錄后復(fù)制

        再次運(yùn)行 node index.js ,得出以下結(jié)果:

        hello cors
        [Function: middlewareWrapper]

        為什么會(huì)打印出 hello cors 呢?因?yàn)閞equire模塊的時(shí)候,引入的是該模塊package.json文件中main字段指向的文件。而這個(gè)js文件會(huì)自動(dòng)執(zhí)行,跟require引用本地js文件是相同的。

        packjson文檔

        在npm的官方網(wǎng)站中可以找到關(guān)于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.

        在以上說明中可以得出以下結(jié)論:

        • main字段是一個(gè)模塊ID,是程序的主入口。

        • 當(dāng)使用require("xxx")的時(shí)候,導(dǎo)入的是main字段對(duì)應(yīng)的js文件里的module.exports。

        所以require導(dǎo)入模塊的時(shí)候,是運(yùn)行的對(duì)應(yīng)模塊package.json中main字段指定的文件。

        推薦學(xué)習(xí):《node視頻教程》

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)
        主站蜘蛛池模板: 无码日韩精品一区二区人妻| 国产精品免费观看| 999精品在线| 亚洲精品A在线观看| 四虎精品影院4hutv四虎| 亚洲国产精品无码久久98| 久久精品国产一区二区三区不卡| 亚洲国产精品久久久久婷婷老年| 国产欧美日韩精品a在线观看 | 亚洲精品人成无码中文毛片| 国产精品成人99久久久久| 国产精品久久久久影院嫩草| 久久精品夜夜夜夜夜久久| 亚洲精品无码永久在线观看你懂的| 久草热8精品视频在线观看| 1区1区3区4区产品芒果精品| 精品视频第一页| 国产精品亚洲精品| 99re久久精品国产首页2020| 国产乱人伦偷精品视频AAA| 亚洲AV永久无码精品水牛影视| 亚洲国产精品一区二区第一页免| 久久996热精品xxxx| 精品国产呦系列在线观看免费 | 欧美日韩精品在线| 国产精品一久久香蕉国产线看| 91精品全国免费观看青青| 2021久久国自产拍精品| 99热门精品一区二区三区无码| avtt天堂网久久精品| 国产精品成人观看视频国产| 99久久99这里只有免费的精品| 99精品在线观看| 久久国产精品99久久久久久老狼| 欧美精品免费线视频观看视频| 久久精品国产只有精品2020| 四虎精品影院永久在线播放| 国产精品国产三级国产潘金莲| 国产亚洲午夜高清国产拍精品 | 日韩精品无码人妻一区二区三区 | 国产A级毛片久久久精品毛片 |