完全面向於初學者的Node.js指南

來源:互聯網
上載者:User

完全面向於初學者的Node.js指南

新的上班時間是周二至周六,工作之餘當然要堅持學習啦。

希望這篇文章能解決你這樣一個問題:“我現在已經下載好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會執行並返回結果,例子:

  
  1. $ node 
  2. > console.log('Hello World'); 
  3. Hello World 
  4. undefined 

PS:上一個例子的undefined來自於console.log的傳回值。

方式二:CMD 下輸入node 檔案名稱當然需要先CD到該目錄)。例子:

  
  1. hello.js 下的代碼: 
  2. console.log('Hello World'); 
  3. $ node hello.js 
  4. Hello World 

Doing Something Useful - File I/O

使用純粹的Js原生代碼是有趣但是不利於工程開發的,Node.JS提供了一些有用的庫modules),下面是一個使用Node.js提供的庫分析檔案的例子:

  
  1. example_log.txt 
  2. 2013-08-09T13:50:33.166Z A 2 
  3. 2013-08-09T13:51:33.166Z B 1 
  4. 2013-08-09T13:52:33.166Z C 6 
  5. 2013-08-09T13:53:33.166Z B 8 
  6. 2013-08-09T13:54:33.166Z B 5 

我們做的第一件事情是讀出該檔案的所有內容。

  
  1. my_parser.js 
  2.  
  3. // Load the fs (filesystem) module 
  4. var fs = require('fs'); 
  5.  
  6. // Read the contents of the file into memory. 
  7. fs.readFile('example_log.txt', function (err, logData) { 
  8.    
  9. // If an error occurred, throwing it will 
  10.   // display the exception and end our app. 
  11.   if (err) throw err; 
  12.    
  13. // logData is a Buffer, convert to string. 
  14.   var text = logData.toString(); 
  15. }); 

filesystem (fs 的API ref) module 提供了一個可以非同步讀取檔案並且結束後執行回調的函數,內容以 Buffer的形式返回一個byte數組),我們可以調用toString() 函數,將它轉換成字串。

現在我們再來添加解析部分的代碼。

 
  1. my_parser.js 
  2.  
  3. // Load the fs (filesystem) module. 
  4. var fs = require('fs');//  
  5.  
  6. // Read the contents of the file into memory. 
  7. fs.readFile('example_log.txt', function (err, logData) { 
  8.    
  9. // If an error occurred, throwing it will 
  10.   // display the exception and kill our app. 
  11.   if (err) throw err; 
  12.    
  13. // logData is a Buffer, convert to string. 
  14.   var text = logData.toString(); 
  15.    
  16. var results = {}; 
  17.  
  18. // Break up the file into lines. 
  19.   var lines = text.split('\n'); 
  20.    
  21. lines.forEach(function(line) { 
  22.     var parts = line.split(' '); 
  23.     var letter = parts[1]; 
  24.     var count = parseInt(parts[2]); 
  25.      
  26. if(!results[letter]) { 
  27.       results[letter] = 0; 
  28.     } 
  29.      
  30. results[letter] += parseInt(count); 
  31.   }); 
  32.    
  33. console.log(results); 
  34.   // { A: 2, B: 14, C: 6 } 
  35. }); 

Asynchronous Callbacks

剛才的例子中使用到了非同步回調,這在Node.Js編碼中是廣泛被使用的,究其原因是因為Node.Js是單線程的可以通過某些特殊手段變為多線程,但一般真的不需要這麼做)。故而需要各種非阻塞式的操作。

這種非阻塞式的操作有一個非常大的優點:比起每一個請求都建立一個線程的Web Server。Node.Js在高並發的情況下,負載是小得多的。

Doing Something Useful - HTTP Server

我們來運行一個HTTP server吧, 直接複製 Node.js homepage.上的代碼就可以了。

  
  1. my_web_server.js 
  2.  
  3.     var http = require('http'); 
  4.  
  5.     http.createServer(function (req, res) { 
  6.       res.writeHead(200, {'Content-Type': 'text/plain'}); 
  7.       res.end('Hello World\n'); 
  8.     }).listen(8080); 
  9.  
  10.     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開發的例子:

  
  1. my_static_file_server.js 
  2.  
  3. var express = require('express'), 
  4.     app = express(); 
  5.  
  6.  
  7.  
  8. app.use(express.static(__dirname + '/public')); 
  9.  
  10. app.listen(8080); 
  11.  
  12. $ node my_static_file_server.js 

這樣就建立了一個檔案伺服器。入油鍋我們在 /public 檔案夾放了一個"my_image.png" 。我們就可以在瀏覽器輸入http://localhost:8080/my_image.png 來擷取這個圖片. 當然,Express 還提供了非常多的其它功能。

Code Organization

剛才的例子中我們使用的都是單個檔案,而實際的開發中,我們會設計到代碼如何組織的問題。

我們試著將最開始的文字解析程式重新組織。

  
  1. parser.js 
  2.  
  3. // Parser constructor. 
  4. var Parser = function() { 
  5.  
  6. }; 
  7.  
  8. // Parses the specified text. 
  9. Parser.prototype.parse = function(text) { 
  10.    
  11. var results = {}; 
  12.    
  13. // Break up the file into lines. 
  14.   var lines = text.split('\n'); 
  15.    
  16. lines.forEach(function(line) { 
  17.     var parts = line.split(' '); 
  18.     var letter = parts[1]; 
  19.     var count = parseInt(parts[2]); 
  20.      
  21. if(!results[letter]) { 
  22.       results[letter] = 0; 
  23.     } 
  24.      
  25. results[letter] += parseInt(count); 
  26.   }); 
  27.    
  28. return results; 
  29. }; 
  30.  
  31. // Export the Parser constructor from this module. 
  32. module.exports = Parser; 

關於這裡的exports 的含義請參考我的部落格:Node.Js學習01: Module System 以及一些常用Node Module.

 
  1. my_parser.js 
  2.  
  3. // Require my new parser.js file. 
  4. var Parser = require('./parser'); 
  5.  
  6. // Load the fs (filesystem) module. 
  7. var fs = require('fs'); 
  8.  
  9. // Read the contents of the file into memory. 
  10. fs.readFile('example_log.txt', function (err, logData) { 
  11.    
  12. // If an error occurred, throwing it will 
  13.   // display the exception and kill our app. 
  14.   if (err) throw err; 
  15.    
  16. // logData is a Buffer, convert to string. 
  17.   var text = logData.toString(); 
  18.    
  19. // Create an instance of the Parser object. 
  20.   var parser = new Parser(); 
  21.    
  22. // Call the parse function. 
  23.   console.log(parser.parse(text)); 
  24.   // { A: 2, B: 14, C: 6 } 
  25. }); 

這樣,文字解析的部分就被抽離了出來。

Summary

Node.js 是強大而靈活的。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.