Node.js - 節點:連結、穿越
  • Present to you by Andy Pan @ NTUOSC
  • 2016/10/17

自介

臺大資工系二年級

  • Both a NodeJS enthusiast and a front-end developer. Write code to explore any possibilities, not seeking the answers, but to understand the questions.

Prologue

  1. 安裝 Node.js
Windows、Mac… https://nodejs.org/en/
建議裝 v4.0 以上的版本,v4~v6 的功能差異不大,主要的差異在 ES6 的支援程度 (新一代 JavaScript 語言規範),可參考支援度比較

安裝完請在 Terminal 上測以下指令:

$ node -v
v4.6.0
$ npm -v
3.10.6
$ yarn -V  # or this
0.15.1

npm 建議更新到 v3,或是裝潮潮的 yarn 也可以 😋

先備知識

略熟 JavaScript 語法、對網路有基本認識
熟悉事件和 callback 用法
開發網路服務的經驗,例如開發 bot (非必須)

REPL

在 Terminal 輸入 node,會進入互動模式 (Read-Eval-Print Loop),便於測試指令。很像是瀏覽器裡的 console。

JavaScript 語法複習 + ES6

為了示範方便,介紹一些 ES6 較為人熟知的新語法。你手邊的瀏覽器不一定支援,但 Node v4+ 應可以順利支援。

Arrow function: 一種函數的簡記法,不會建立新的 this/arguments
var sqr = function (x) { return x * x; };
// is the same as...
var sqr = (x) => x * x;

Template string: 一種建立字串的方式,可以在裡面嵌入表達式
var goodMorning = '早安您好', happy = '平安喜樂', share = '分享';
console.log(goodMorning + ',' + happy + ',認同請' + share + '。');
// is the same as...
console.log(`${goodMorning}${happy},認同請${share}。`);

Dive into the world of Node

Node 是一個執行 JavaScript 的環境。”Node” 中文是「結點」,設計的目的是要用 JavaScript 的語法,借重 JS 開發者在前端的開發經驗,打造出強大、高效能的網路服務。
相較於瀏覽器,Node 缺少了「顯示」的部份,最上層的物件不是 window、沒有 DOM,留下純粹的 JavaScript。但這不代表它的能力較瀏覽器弱。瀏覽器的 code 像是關在一個隔離的環境一般,能力受制於。Node 透過 API 和原生的函式庫,使應用程式能進行更貼近系統底層的操作。