Node.js 簡介
Nodejs 是什么?
Node.js 不是一種獨(dú)立的語言,也不是一個 JavaScript 框架,更不是瀏覽器的庫。Node.js 是一個讓 JavaScript 運(yùn)行在服務(wù)端的開發(fā)平臺,它讓 JavaScript 跟 PHP 、Python 等腳本語言一樣可以作為后端語言。
Node.js 能干嘛
Node.js 適合那種高并發(fā)的應(yīng)用場景,比如 即時聊天程序。因為 Node.js 內(nèi)置了 HTTP 服務(wù)器的支持。也就是說不用像 PHP 等其他后端語言一樣,還要通過 Apache 服務(wù)器等,直接幾行代碼,在V8引擎上一跑,一個簡單的服務(wù)器就搭建好了。
異步式 I/O 與事件驅(qū)動
這是 Node.js 最大的特性了。傳統(tǒng)架構(gòu)應(yīng)對高并發(fā)的方案是多線程并行。而 Node.js 使用的是單線程模型,它在執(zhí)行過程中有一個事件隊列,當(dāng)程序執(zhí)行到耗時長的 I/O 請求時,不會說一直等待,而是執(zhí)行其他操作,等該 I/O 請求完成后,利用事件循環(huán)再次調(diào)出來執(zhí)行。
舉個例子
let fs = require('fs')
fs.readFile('./Git.md', 'utf-8', (err, data) => {
if (err) {
throw err
}
console.log(data)
}
)
console.log('hhh')
執(zhí)行結(jié)果是,先看到打印的 hhh ,然后才是打印出讀取文件 Git.md 的內(nèi)容。這是因為 fs.readFile()
它是異步執(zhí)行的。
Node.js 入門
-
hello world
- 新建一個文件例如 hello.js ,然后寫上
console.log('hello node.js')
打開命令行工具,執(zhí)行node hello.js
注意文件路徑要對得上。 - 也可以直接在命令行里運(yùn)行代碼,只需執(zhí)行
node
進(jìn)入即可Ctrl + C
就是退出。
hello node.js - 新建一個文件例如 hello.js ,然后寫上
-
搭建 HTTP 服務(wù)器
const http = require('http') const myBrowser = require('child_process') const PORT = 3000 let server = http.createServer server.on('request', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }) res.write('<h1>Hello Node.js</h1>'); res.end(); }) server.listen(PORT) console.log('http server listen to port ' + PORT) myBrowser.exec('start http://127.0.0.1:' + PORT)
http服務(wù)器 -
模塊的創(chuàng)建和引入
Node.js 的模塊是參考 CommonJS 規(guī)范的。
- exports
// hello.js 文件 module.exports = function (){ console.log('hello CommonJS'); }
- require
let hello = require('./hello'); hello(); // 打印出 hello CommonJS
image.png-
單次加載
第一次加載后會放到緩存,再次加載只是直接從緩存里拿來用而已。
參考資料
- Node.js 開發(fā)指南