Node.js[2] Hello Node


上一篇俯瞰NPM,這次該進入node開發的主題了。

准備

Node安裝

windows下直接使用安裝包安裝;其他平台也有對應的安裝包或下載源碼安裝。安裝完畢后請使用如下命令驗證,如果一切順利可以看到node版本號:

$ node -v

Node文檔

推薦使用在線版本;如需離線版本可從github clone node代碼,linux下可編譯出完整的api文檔。

$ git clone git://github.com/joyent/node.git
$ cd node
$ make doc

Git

git是一個分布式版本控制系統,不同於svn的中心控制,git在每個節點上都有一個完整的版本庫;此外和svn最大的不同在於branch的管理上,這也造就了兩種截然不同的版本控制風格。更多git細節請參考開源git教程《ProGit》。

windows下比較流行msysgit;Ubuntu下可以通過應用中心直接安裝;其他平台多通過源碼安裝。

git雖然命令眾多,但是初期常用的也就下面幾個:

git clone,從服務器上拷貝一個版本庫(git就是這樣,整個庫都會拉下來)

git add,本地新增文件,添加至本地的git版本庫(還未提交)

git commit,提交所有修改,一般合並git add和git commit:

$ git commit -a -m 'some comment'

git push,將本地版本庫推送至服務器(通常就是github)

$ git push –u master origin

Hello Node

先跑起來

下面的demo來自nodejs.org(有小改):

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

將其保存為hello.js,命令行中輸入

$ node hello.js

Server running at http://127.0.0.1:1337/

一個簡易的http server就運行起來了,瀏覽器中敲入

http://127.0.0.1:1337/

逐行分析

//node使用javascript作為其應用層編程語言,所以node程序的語法和js無差
//聲明node自定義模塊(http)
var http = require('http');
//創建並啟動http server
http.createServer(
//每次請求到來觸發如下回調
function (req, res) {
  //輸出http header
  res.writeHead(200, {'Content-Type': 'text/plain'});
  //輸出http body,並完成response操作
  res.end('Hello World\n');
//監聽 127.0.0.1:1337 的請求,
}).listen(1337, '127.0.0.1');
//console.log和瀏覽器中使用習慣一致
//這里會將日志打印至標准輸出(即命令行界面)
console.log('Server running at http://127.0.0.1:1337/');

A Simple Static Server

這里提供一個較簡單的靜態文件服務器代碼(下載完整demo),感興趣的同學可以對照API文檔:

var
    http = require('http'),
    url = require('url'),
    fs = require('fs');
// 創建並啟動服務器
// 瀏覽器地址欄輸入 http://127.0.0.1:3001/demo.html
http.createServer(function (req, res) {
    var pathname = __dirname + '/public' + url.parse(req.url).pathname;
    // 讀取本地文件
    // node的設計理念之一:web server每個處理環節都是異步的
    fs.readFile(pathname, function (err, data) {
        if (err) {
            res.writeHead(500);
            res.end('500');
        } else {
            // 這里可以對文件類型判斷,增加Content-Type
            res.end(data);
        }
    });
}).listen(3001, function () {
        console.log('http.Server started on port 3001');
    });


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM