Contents
  1. 1. 命令行参数(Baby Steps)
  2. 2. 同步IO(My First I/O)
  3. 3. 异步IO(My First Async I/O)

learnyounode是nodeschool.io上学习 Node.js 的基础:如异步 I/O、http 等的教程。本文用于简单记录自己的学习过程。

1
2
3
4
# 安装
$ npm install learnyounode -g
# 运行
$ learnyounode

画面如下
2.png


命令行参数(Baby Steps)

全局对象process拥有一个名为 argv 的属性,该属性是一个数组,数组中包含了整条命令的所有部分。

1
$ node program.js 1 2 3

对应数组

1
[ 'node', '/path/to/your/program.js', '1', '2', '3' ]

process.argv可获得命令行参数数组

  • 数组的第一个元素(index是0)永远都会是 node,并且第二个参数(index是1)总是指向你的程序的路径。
  • 数组的所有元素都是字符串类型的。如果需要强制转换成数字。可以通过加上 + 前缀,或者将其传给 Number() 来解决。例如: +process.argv2 或者 Number(process.argv2)。

同步IO(My First I/O)

同步IO就是程序要等待IO操作完成才可以继续执行(阻塞)。

以下是同步读取文本文件,并输出文本行数的例子:

1
2
3
4
5
var fs=require('fs');     //加载Node的核心模块之一"fs",并通过变量fs访问。
var buf=fs.readFileSync(process.argv[2]); //同步读取,返回一个包含文件完整内容的 "Buffer"对象。
var str=buf.toString();
var split_strs=str.split('\n'); //计算文本行数
console.log(split_strs.length-1);

  • 模块fs 中所有的同步(或者阻塞)的操作文件系统的方法名都会以 Sync 结尾。
  • Buffer对象 是 Node 用来高效处理数据的方式,无论该数据是 ascii 还是二进制文件,或者其他的格式。Buffer 可以很容易地通过调用 toString() 方法转换为字符串。

  • 注意,通过修改 fs.readFileSync(process.argv[2], 'utf8') 可以省略 .toString() ,直接得到字符串。


异步IO(My First Async I/O)

异步IO就是程序不用依赖I/O操作实际完成,即可进行后续任务(非阻塞)。

以下是异步读取文本文件,并输出文本行数的例子:

1
2
3
4
5
6
7
var fs=require('fs');
var callback=function(err,data){
if(!err){
console.log(data.toString().split('\n').length-1);
}
};
fs.readFile(process.argv[2],callback); //异步读取,传递回调函数

同步IO和异步IO

  • 适用场景

    Usually things that have to talk to hard drives or networks will be asynchronous. If they just have to access things in memory or do some work on the CPU they will be synchronous. The reason for this is that I/O is reallyyy reallyyy sloowwww.

  • 深入浅出Node.js(五):初探Node.js的异步I/O实现
Contents
  1. 1. 命令行参数(Baby Steps)
  2. 2. 同步IO(My First I/O)
  3. 3. 异步IO(My First Async I/O)