新的上班時間是周二至周六,工作之余當然要堅持學習啦。
希望這篇文章能解決你這樣一個問題:“我現在已經下載好Node.Js了,該做些什么呢?”
原文URL:http://blog.modulus.io/absolute-beginners-guide-to-nodejs
本文的組成:上文的翻譯以及小部分自己的理解。所有文章中提到的JS代碼,都是經過測試,可運行並產生正確結果的。
What is Node.js?
關於Node.Js,要注意一點:Node.js本身並不是像IIS,Apache一樣的webserver,它是一個JavaScript 的運行環境。當我們需要搭建一個HTTP 服務器的時候,我們可以借助Node.Js提供的庫快捷的寫一個。
Installing Node
Node.js 安裝是非常方便的,如果你在用Windows or Mac,去這個頁面就可以了download page.
I've Installed Node, now what?
以WINDOWS為例,一旦安裝好Node.Js之后,可以通過兩種不同方式來調用Node。
方式一:CMD 下輸入node,進入交互模式,輸入一行行的JS代碼,Node.Js會執行並返回結果,例子:
$ node
> console.log('Hello World');
Hello World
undefined
PS:上一個例子的undefined來自於console.log的返回值。
方式二:CMD 下輸入node 文件名(當然需要先CD到該目錄)。例子:
hello.js 下的代碼:
console.log('Hello World');$ node hello.js Hello World
Doing Something Useful - File I/O
使用純粹的Js原生代碼是有趣但是不利於工程開發的,Node.JS提供了一些有用的庫(modules),下面是一個使用Node.js提供的庫分析文件的例子:
example_log.txt
2013-08-09T13:50:33.166Z A 2 2013-08-09T13:51:33.166Z B 1 2013-08-09T13:52:33.166Z C 6 2013-08-09T13:53:33.166Z B 8 2013-08-09T13:54:33.166Z B 5
我們做的第一件事情是讀出該文件的所有內容。
my_parser.js
// Load the fs (filesystem) module var fs = require('fs'); // Read the contents of the file into memory. fs.readFile('example_log.txt', function (err, logData) { // If an error occurred, throwing it will // display the exception and end our app. if (err) throw err; // logData is a Buffer, convert to string. var text = logData.toString(); });
filesystem (fs 的API ref) module 提供了一個可以異步讀取文件並且結束后執行回調的函數,內容以 Buffer的形式返回(一個byte數組),我們可以調用toString() 函數,將它轉換成字符串。
現在我們再來添加解析部分的代碼。
my_parser.js
// Load the fs (filesystem) module. var fs = require('fs');// // Read the contents of the file into memory. fs.readFile('example_log.txt', function (err, logData) { // If an error occurred, throwing it will // display the exception and kill our app. if (err) throw err; // logData is a Buffer, convert to string. var text = logData.toString(); var results = {}; // Break up the file into lines. var lines = text.split('\n'); lines.forEach(function(line) { var parts = line.split(' '); var letter = parts[1]; var count = parseInt(parts[2]); if(!results[letter]) { results[letter] = 0; } results[letter] += parseInt(count); }); console.log(results); // { A: 2, B: 14, C: 6 } });
Asynchronous Callbacks
剛才的例子中使用到了異步回調,這在Node.Js編碼中是廣泛被使用的,究其原因是因為Node.Js是單線程的(可以通過某些特殊手段變為多線程,但一般真的不需要這么做)。故而需要各種非阻塞式的操作。
這種非阻塞式的操作有一個非常大的優點:比起每一個請求都創建一個線程的Web Server。Node.Js在高並發的情況下,負載是小得多的。
Doing Something Useful - HTTP Server
我們來運行一個HTTP server吧, 直接復制 Node.js homepage.上的代碼就可以了。
my_web_server.js
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(8080); console.log('Server running on port 8080.');
運行以上代碼之后就可以訪問http://localhost:8080 就能看到結果啦。
上面的例子顯然過於簡單,如果我們需要建立一個真正的web server。我們需要能夠檢查什么正在被請求,渲染合適的文件,並返回。而好消息是,Express已經做到這一點了。
Doing Something Useful - Express
Express 是一個可以簡化開發的框架。我們執行npm install 來安裝這個package。
$ cd /my/app/location $ npm install express
指令執行完畢后,Express相關的文件會被放到應用目錄下的node_modules文件夾中。下面是一個使用Express開發的例子:
my_static_file_server.js
var express = require('express'), app = express();app.use(express.static(__dirname + '/public')); app.listen(8080);$ node my_static_file_server.js
這樣就建立了一個文件服務器。入油鍋我們在 /public 文件夾放了一個"my_image.png" 。我們就可以在瀏覽器輸入http://localhost:8080/my_image.png 來獲取這個圖片. 當然,Express 還提供了非常多的其它功能。
Code Organization
剛才的例子中我們使用的都是單個文件,而實際的開發中,我們會設計到代碼如何組織的問題。
我們試着將最開始的文字解析程序重新組織。
parser.js
// Parser constructor. var Parser = function() { }; // Parses the specified text. Parser.prototype.parse = function(text) { var results = {}; // Break up the file into lines. var lines = text.split('\n'); lines.forEach(function(line) { var parts = line.split(' '); var letter = parts[1]; var count = parseInt(parts[2]); if(!results[letter]) { results[letter] = 0; } results[letter] += parseInt(count); }); return results; }; // Export the Parser constructor from this module. module.exports = Parser;
關於這里的exports 的含義請參考我的博客:Node.Js學習01: Module System 以及一些常用Node Module.
my_parser.js
// Require my new parser.js file. var Parser = require('./parser'); // Load the fs (filesystem) module. var fs = require('fs'); // Read the contents of the file into memory. fs.readFile('example_log.txt', function (err, logData) { // If an error occurred, throwing it will // display the exception and kill our app. if (err) throw err; // logData is a Buffer, convert to string. var text = logData.toString(); // Create an instance of the Parser object. var parser = new Parser(); // Call the parse function. console.log(parser.parse(text)); // { A: 2, B: 14, C: 6 } });
這樣,文字解析的部分就被抽離了出來。
Summary
Node.js 是強大而靈活的。
