前面讲到Node.js的特性主要有:单线程、非阻塞IO、Google V8引擎、事件驱动。
举个简单例子来说明下Node.js的非阻塞IO的特性。
以一个读取文件内容的脚本readme.js为例:
var fs = require('fs'), fileContent = 'nothing'; fs.readFile(__filename, "utf-8", function(err, file) { if(err) { console.log(err); return; } fileContent = file; console.log('finished reading file..\n'); });
console.log('file content: ' +fileContent + ' \n');
这个脚本读取当前脚本文件的内容,并输出。__filename是node.js的一个全局变量,它的值为当前文件的绝对路径。 用node命令执行该脚本:
程序先执行了最后面的file content打印,等到文件读取完成后,才打印“finished reading file ...”.
这就是Node.js的非阻塞IO特性。readFile函数就是异步非阻塞读取文件内容。所以后面的程序并不会等待该函数执行完后才执行。这对于很多服务器端处理程序来说,可以说是一个极具诱惑力的特性。
把上述脚本代码作如下修改:
再次运行,就可以得到我们所要的结果了:var fs = require('fs'), fileContent = 'nothing'; fs.readFile(__filename, "utf-8", function(err, file) { if(err) { console.log(err); return; } fileContent = file; console.log('file content: ' +fileContent + ' \n'); }); console.log('waiting for the file reading...\n');