Node.js 從小白到菜鳥系列文章記錄本人從一個(gè)小白到依靠 Node.js 混口飯吃的歷程。此篇為 Node.js 從小白到菜鳥系列文章的第零篇,介紹一些學(xué)習(xí) Node.js 的預(yù)備知識(shí)與 Node.js 安裝使用。此篇文章的內(nèi)容一定要讀懂,這些內(nèi)容是 Node.js 的工作方式與核心概念。
Node.js 安裝
- Windows 用戶可以在 Node.js 官網(wǎng) 下載安裝包
- *nix 和 macOS 用戶可以使用 nvm 進(jìn)行安裝。具體安裝方法參考 nvm 文檔
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.json中scripts中配置
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
exports 和 module.exports 是 Node.js 提供的文件導(dǎo)出機(jī)制,require 引入的是 module.exports。
初始狀態(tài) module.exports 值為 {},exports 與 module.exports 指向同一塊數(shù)據(jù),這時(shí)可以通過 exports.${name} 進(jìn)行賦值并導(dǎo)出。當(dāng)對(duì) module.exports 進(jìn)行賦值后如 module.exports = function () {},exports 與 module.exports 不再指向同一塊數(shù)據(jù),這時(shí)如果在其他文件中 require 僅能得到 module.exports 導(dǎo)出的內(nèi)容,而使用 exports.${name} 賦值的數(shù)據(jù)是無法導(dǎo)出的。所以常見到一種寫法 exports = module.exports = function () {},這樣做又使得 exports 與 module.exports 指向同一塊數(shù)據(jù)。
module.exports 導(dǎo)出的內(nèi)容可以是任何合法的 JavaScript 對(duì)象(String、Number、Function、JSON 等等)。