完全面向于初学者的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 是强大而灵活的。

 

 

 
责任编辑:王雪燕 来源: 博客园
相关推荐

2010-08-26 15:47:09

vsftpd安装

2024-04-28 10:56:34

Next.jsWeb应用搜索引擎优化

2022-04-24 15:21:01

MarkdownHTML

2019-03-29 16:40:02

Node.js多线程前端

2013-12-20 14:47:23

ember.js

2010-06-13 11:13:38

UML初学者指南

2022-07-22 13:14:57

TypeScript指南

2022-10-10 15:28:45

负载均衡

2021-05-10 08:50:32

网络管理网络网络性能

2022-03-28 09:52:42

JavaScript语言

2023-07-03 15:05:07

预测分析大数据

2023-07-28 07:31:52

JavaScriptasyncawait

2020-06-03 10:00:30

Kubernetes容器开发

2022-09-05 15:36:39

Linux日志记录syslogd

2018-10-28 16:14:55

Reactreact.js前端

2012-03-14 10:56:23

web app

2023-02-10 08:37:28

2021-05-06 09:00:00

JavaScript静态代码开发

2014-04-01 10:20:00

开源Rails

2020-08-16 13:10:46

TensorFlow深度学习数据集
点赞
收藏

51CTO技术栈公众号