原文URL:http://blog.modulus.io/absolute-beginners-guide-to-nodejsjava
本文的组成:上文的翻译以及小部分本身的理解。全部文章中提到的JS代码,都是通过测试,可运行并产生正确结果的。node
What is Node.js?
关于Node.Js,要注意一点:Node.js自己并非像IIS,Apache同样的webserver,它是一个JavaScript 的运行环境。当咱们须要搭建一个HTTP 服务器的时候,咱们能够借助Node.Js提供的库快捷的写一个。web
Installing Node
Node.js 安装是很是方便的,若是你在用Windows or Mac,去这个页面就能够了download page.express
I've Installed Node, now what?
以WINDOWS为例,一旦安装好Node.Js以后,能够经过两种不一样方式来调用Node。npm
方式一:CMD 下输入node,进入交互模式,输入一行行的JS代码,Node.Js会执行并返回结果,例子:api
$ 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 是强大而灵活的。