node基礎(chǔ)
簡概:Node.js 就是運(yùn)行在服務(wù)端的 JavaScript。運(yùn)行的核心是Google的V8引擎
- 安裝:
node中文網(wǎng) - 查看版本:
node -v - 創(chuàng)建一個(gè)js程序 hello.js輸入
console.log("hello")
然后在終端執(zhí)行node hello.js
- 創(chuàng)建應(yīng)用:一個(gè)node應(yīng)用主要由3個(gè)部分組成
- node.js的模塊 這部分用require導(dǎo)入
- 創(chuàng)建服務(wù)器:服務(wù)器可以監(jiān)聽客戶端的請求,類似于 Apache 、Nginx 等 HTTP 服務(wù)器。
- 接收請求與響應(yīng)請求
服務(wù)器很容易創(chuàng)建,客戶端可以使用瀏覽器或終端發(fā)送 HTTP 請求,服務(wù)器接收請求后返回響應(yīng)數(shù)據(jù)
第一個(gè)應(yīng)用
touch app.js- 打開app.js輸入如下代碼
//1.導(dǎo)入http模塊
var http = require("http")
//2.創(chuàng)建服務(wù),返回一個(gè)服務(wù)對象并且監(jiān)聽8888端口!
//3.在服務(wù)里面創(chuàng)建回調(diào)函數(shù),接受請求和相應(yīng)
http.createServer(function (request, response) {
// 發(fā)送 HTTP 頭部
// HTTP 狀態(tài)值: 200 : OK
// 內(nèi)容類型: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// 發(fā)送響應(yīng)數(shù)據(jù) "Hello World"
response.end('Hello World\n');
}).listen(8888);
// 終端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
我們在終端執(zhí)行node app.js
然后在localhost:8888上可以看到返回的數(shù)據(jù)
NPM
npm是隨同NodeJS一起安裝的包管理工具 npm -v查看版本
- 升級
sudo npm install npm -g
注釋:當(dāng)執(zhí)行npm install后,會在項(xiàng)目中產(chǎn)生package.json以及相對應(yīng)的node_modules文件,這個(gè)是npm管理的文件
- 和諧外網(wǎng)用淘寶鏡像(cnpm)
npm install -g cnpm --registry=https://registry.npm.taobao.org
- -g全局安裝和本地安裝區(qū)別:本地安裝在項(xiàng)目的node_modules里面 ,全局安裝在/usr/local 下或者你 node 的安裝目錄!
- 其他命令:
npm list全局安裝了哪些npm list -g模塊版本npm list grunt - 錯(cuò)誤:
npm err! Error: connect ECONNREFUSED 127.0.0.1:8087
解決:npm config set proxy null