第一次學Node.js就上手:自學入門筆記

Samuel
Be a happy coder 快樂學程式
4 min readJan 10, 2019

這篇文章適合誰

這篇文章適合想學習Node.js這個框架對於JavaScript並且對於JavaScript有一些認識的讀者,本篇文章將用hello world這個在學習每個程式語言時都會先接觸到的範例,讓你先初步認識Node.js。

何謂Node.js

Node.js顧名思義便是使用JavaScript語言作為基礎的框架,特別的是,相對於jQuery或是YUI等在瀏覽器中運行使用的JavaScript框架,Node.js是作為網站程式的後端框架,就如同PHP或是Java一般開發網站。

換句話說,JavaScript不只可以跑在瀏覽器中,還可以當做網站的伺服器。主要的原因是在於隨著Gmail等AJAX網站以及技術的興起,許多的程式開發者紛紛投入心力鑽研JavaScript,並且有許多開發心得、優化技巧陸續被發掘,加上瀏覽器之間的競爭越來越激烈,JavaScript的執行效能持續性的突破,因此最終便誕生了Node.js。

Hello World

在使用Node.js創建“Hello, World”應用程序之前,讓我們看看Node.js的應用程序的部分。Node.js應用程序由以下三個重要組成部分:

導入需要模塊: 我們使用require指令加載Node.js模塊。

創建服務器: 服務器將監聽類似Apache HTTP Server客戶端的請求。

讀取請求,並返回響應: 在前麵的步驟中創建的服務器將讀取客戶端發出的HTTP請求,它可以從一個瀏覽器或控製台並返回響應。

導入所需要的模塊

我們使用require指令來加載HTTP模塊和存儲返回HTTP,例如HTTP變量,如下所示:

var http = require("http");

在接下來的步驟中,我們使用HTTP創建實例,並調用http.createServer()方法來創建服務器實例,然後使用服務器實例監聽相關聯的方法,把它綁定在端口8081。 通過它使用參數的請求和響應函數。編寫示例實現返回 “Hello World”

http.createServer(function (request, response) {   // Send the HTTP header 
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

測試請求和響應

讓我們將以上步驟儲存成一個名為main.js的檔案,並啟動HTTP伺服器

var http = require("http");http.createServer(function (request, response) {   // Send the HTTP header 
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

現在執行main.js來啟動服務器

$ node main.js

再來就可以去瀏覽器輸入http://127.0.0.1:8081/網址就看可以在網頁上看到Hello World~

結語

已上是關於Node.js的一些基礎知識,希望能夠藉由這篇文章幫助到你,當然還有許多有關Node.js框架的內容沒有收錄進來,如果希望可以看到更多內容,歡迎來到我們快樂學程式的官網來逛逛。網址連結:https://www.happycoding.today/posts

Originally published at www.happycoding.today.

--

--