Node.js 從小白到菜鳥 0 — 預(yù)備知識(shí)

Node.js 從小白到菜鳥系列文章記錄本人從一個(gè)小白到依靠 Node.js 混口飯吃的歷程。此篇為 Node.js 從小白到菜鳥系列文章的第零篇,介紹一些學(xué)習(xí) Node.js 的預(yù)備知識(shí)與 Node.js 安裝使用。此篇文章的內(nèi)容一定要讀懂,這些內(nèi)容是 Node.js 的工作方式與核心概念。

Node.js 安裝

NPM

NPM 現(xiàn)在的版本中已經(jīng)集成到 Node.js 安裝包中,所以安裝好 Node.js 后就已經(jīng)可以使用 npm 命令了。NPM 是 Node.js 的包管理工具,可以使用 NPM 來安裝開源模塊幫助我們更有效率地開發(fā)。NPM 常用命令如下:

  • npm init:在當(dāng)前目錄初始化項(xiàng)目并生成 package.json
  • npm install:安裝 package.json 中聲明的所有依賴模塊
  • npm install ${module_name} --save:安裝 ${module_name} 模塊并將依賴寫入 package.json
  • npm run ${command}:執(zhí)行命令,命令可在 package.jsonscripts 中配置

package.json 是一個(gè) Node.js 項(xiàng)目的說明文件,其中說明了項(xiàng)目名稱,入口文件,依賴模塊等信息。package.json 示例內(nèi)容如下:

{
  "name": "example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

require

require 是 Node.js 提供的模塊引入機(jī)制??梢砸?.js.json.node 文件。

exports 和 module.exports

exportsmodule.exports 是 Node.js 提供的文件導(dǎo)出機(jī)制,require 引入的是 module.exports。

初始狀態(tài) module.exports 值為 {}exportsmodule.exports 指向同一塊數(shù)據(jù),這時(shí)可以通過 exports.${name} 進(jìn)行賦值并導(dǎo)出。當(dāng)對(duì) module.exports 進(jìn)行賦值后如 module.exports = function () {},exportsmodule.exports 不再指向同一塊數(shù)據(jù),這時(shí)如果在其他文件中 require 僅能得到 module.exports 導(dǎo)出的內(nèi)容,而使用 exports.${name} 賦值的數(shù)據(jù)是無法導(dǎo)出的。所以常見到一種寫法 exports = module.exports = function () {},這樣做又使得 exportsmodule.exports 指向同一塊數(shù)據(jù)。

module.exports 導(dǎo)出的內(nèi)容可以是任何合法的 JavaScript 對(duì)象(String、Number、Function、JSON 等等)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容