学习nodejs——callback, async i/o

来源:互联网 发布:网络还能买彩票吗 编辑:程序博客网 时间:2024/05/19 03:46
CALLBACK
Callbacks are functions that are executed asynchronously, or at a later time. Instead of the code reading top to bottom procedurally, async programs may execute different functions at different times based on the order and speed that earlier functions like http requests or file system reads happen.

举个例子,异步读文件并用console输出:
var fs = require('fs');//'readme.txt'fs.readFile(process.argv[2], 'utf8', function callback(err, data) {     if(err !== true) {       console.log(data);     }});

文件路径作为第一个参数,在shell中用以下命令运行:
node program.js readme.txt

readFile的第二个参数为‘utf8’输出为string,如果不加这个参数,callback的data值返回为一个buffer。

如果要返回输入文件的行数呢? 可以将输出改成:
console.log(data.split('\n').length-1);

FILTERED LS  (nodeschool -> learnyounote)
打印指定路径(第一个参数)下,指定后缀(第二个参数)的所有文件名:


program.js
var fs = require('fs');var file = process.argv[2];var filter = process.argv[3];//'readme.txt'fs.readdir(file, function callback(err, list) {    if(err !== true) {       for(var i = 0; i < list.length; ++i)       {        //  console.log(list[i]);         if( (list[i].split('.')[1]) && list[i].split('.')[1] === filter){           console.log(list[i]);         }       }    }});


0 0
原创粉丝点击