第一個Node.js程序:Hello World!
#查看版本
C:\>node -v
v6.2.0
#查看版本
C:\>node --version
v6.2.0
#終端node命令
C:\>node
>console.log("Hello World");
#新建js文件holleworld.js 在c盤下,內(nèi)容為“console.log("Hello World");”然后使用node命令
C:\>node holleworld.js
node.js官方下載地址:https://nodejs.org/en/download/
windows/ubuntu/centos 下安裝見:http://www.runoob.com/nodejs/nodejs-install-setup.html
創(chuàng)建 Node.js 應(yīng)用
node.js的應(yīng)用模塊
1引入 required 模塊:我們可以使用 require 指令來載入 Node.js 模塊。
2創(chuàng)建服務(wù)器:服務(wù)器可以監(jiān)聽客戶端的請求,類似于 Apache 、Nginx 等 HTTP 服務(wù)器。
3接收請求與響應(yīng)請求: 服務(wù)器很容易創(chuàng)建,客戶端可以使用瀏覽器或終端發(fā)送 HTTP 請求,服務(wù)器接收請求后返回響應(yīng)數(shù)據(jù)。
步驟一、引入 required 模塊
我們使用 require 指令來載入 http 模塊,并將實例化的 HTTP 賦值給變量 http,實例如下:
var http = require("http");
步驟二、創(chuàng)建服務(wù)器
接下來我們使用 http.createServer() 方法創(chuàng)建服務(wù)器,并使用 listen 方法綁定 8888 端口。 函數(shù)通過 request, response 參數(shù)來接收和響應(yīng)數(shù)據(jù)。
實例如下,在你項目的根目錄下創(chuàng)建一個叫 server.js 的文件,并寫入以下代碼:
var http = require('http');
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/');
以上代碼我們完成了一個可以工作的 HTTP 服務(wù)器。
使用 node 命令執(zhí)行以上的代碼:
C:\>node server.js
Server running at http://127.0.0.1:8888/
步驟三、訪問
打開瀏覽器訪問 http://127.0.0.1:8888/ ,你會看到一個寫著 "Hello World"的網(wǎng)頁。
此文章整理轉(zhuǎn)載于 菜鳥教程,僅用于整理學(xué)習(xí)。