完全面向于初学者的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会执行并返回结果,例子:
$ 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 是强大而灵活的。
完全面向于初学者的Node.js指南的更多相关文章
- 专门针对初学者的Node.js教程
转载原文:http://www.csdn.net/article/2013-08-28/2816731-absolute-beginners-guide-to-nodejs Node.js的教程并不缺 ...
- Node.js 指南(迁移到安全的Buffer构造函数)
迁移到安全的Buffer构造函数 移植到Buffer.from()/Buffer.alloc() API. 概述 本指南介绍了如何迁移到安全的Buffer构造函数方法,迁移修复了以下弃用警告: 由于安 ...
- 【转】使用VS开发 Node.js指南
参考:https://www.visualstudio.com/features/node-js-vs 这篇文章主要介绍了使用VS开发 Node.js的方法,主要是使用NTVS(Node.js Too ...
- 初学者的Node.js学习历程
废话篇: 对于我这个新手的不能再白菜的人来说,nodejs的大名都有耳闻,所以说他是一项不可不克服的技能也是可以说的.但是之前没有搞清楚的情况之下胡乱的猜测,是的我对node.js没有一个具体的概念的 ...
- 面向复杂应用,Node.js中的IoC容器 -- Rockerjs/core
Rockerjs Core 项目地址 项目主页 基于 TypeScript 和注解的轻量级IoC容器,提供了依赖注入.面向切面编程及异常处理等功能.Rockerjs Core可在任意工程中引入,是一个 ...
- Node.js学习笔记 01 搭建静态服务器
希望这篇文章能解决你这样一个问题:“我现在已经了解了一些Node.Js基本概念了,怎么搭一台静态服务器呢?” 请参考一下博主的前两篇文章: 完全面向于初学者的Node.js指南 Node.Js的Mod ...
- 10+ 最佳的 Node.js 教程和实例
如果你正在找Node.js的学习资料及指南,那么请继续(阅读),我们的教程将会覆盖即时聊天应用.API服务编写.投票问卷应用.人物投票APP.社交授权. Node.js on Raspberry Pi ...
- Node.js 学习资源
这篇文章编译整理自Stack Overflow的一个如何开始学习Node.js的Wiki帖,这份资源列表在SO上面浏览接近60万次,数千个收藏和顶.特意整理发布到这里,其中添加了部分中文参考资料. 学 ...
- 学习Node.js笔记(一)
一.什么是Node.js 1.1.Node.js是什么 Node.js是用来编写高性能网络服务器的JavaScript工具包 Node.js 是一个基于Chrome JavaScript 运行时建立的 ...
随机推荐
- "开发路上踩过的坑要一个个填起来————持续更新······(7月30日)"
欢迎转载,请注明出处! https://gii16.github.io/learnmore/2016/07/29/problem.html 踩过的坑及解决方案记录在此篇博文中! 个人理解,如有偏颇,欢 ...
- 互联网行业都缺前端工程师-最高offer薪水38k*16
摘要:现在,几乎整个互联网行业都缺前端工程师,不仅在刚起步的创业公司,对上市公司乃至巨头这个问题也一样存在.没错,优秀的前端工程师简直比大熊猫还稀少. 现在,几乎整个互联网行业都缺前端工程师,不仅在刚 ...
- GLES & Shader Language 易错集锦
1. vertex shader 和 fragment shader 通过varying变量传递数据, 如下代码在编译fragment shader时候会提示编译错误 vertex shader F ...
- java学习之(垃圾回收)
程序无法精确控制java垃圾回收的时机,但依然可以强制系统进行垃圾回收--这种强制只是通知系统进行垃圾回收, 但系统是否进行垃圾回收依然不确定.大部分时候,程序强制系统垃圾回收后总会有一些效果,强制系 ...
- malloc、calloc、realloc的区别
(1)C语言跟内存分配方式 <1>从静态存储区域分配. 内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在.例如全局变量.static变量.<2> ...
- HDOJ1010(BFS)
//为什么bfs不行呢,想不通 #include<cstdio>#include<cstring>#include<queue>using namespace st ...
- __main__:1: Warning: Unknown table 'employ' 0L
__main__:1: Warning: Unknown table 'employ' 0L from warnings import filterwarnings import MySQLdb fi ...
- JAVA语法细节(1)
1.变量的作用域 变量的作用域从变量定义的位置开始,到变量所在的那对大括号结束.变量定义内存开辟一块空间用于该变量,变量到达作用域时,该变量从内存中消失. 2.变量的数据类型 变量基本数据类型:byt ...
- 教你快速写出多线程Junit单元测试用例 - GroboUtils
摘自: http://mushiqianmeng.blog.51cto.com/3970029/897786/ 本文出自One Coder博客,转载请务必注明出处: http://www.coderl ...
- [原]POJ1141 Brackets Sequence (dp动态规划,递归)
本文出自:http://blog.csdn.net/svitter 原题:http://poj.org/problem?id=1141 题意:输出添加括号最少,并且使其匹配的串. 题解: dp [ i ...