学习nodejs——callback, async i/o
2015-06-11 10:38
543 查看
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输出:
文件路径作为第一个参数,在shell中用以下命令运行:
readFile的第二个参数为‘utf8’输出为string,如果不加这个参数,callback的data值返回为一个buffer。
如果要返回输入文件的行数呢? 可以将输出改成:
FILTERED LS (nodeschool -> learnyounote)
打印指定路径(第一个参数)下,指定后缀(第二个参数)的所有文件名:
program.js
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]); } } } });
相关文章推荐
- 【Leetcode Algorithm】Remove Nth Node From End of List
- Ubuntu 11.10 H3C iNode 客户端安装
- ERROR: Can't get master address from ZooKeeper; znode data == null
- leetcode之Count Complete Tree Nodes
- 推荐15个 Node.js 开发工具
- Format aborted in 格式化namenode 失败的原因
- [LeetCode] Count Complete Tree Nodes 求完全二叉树的节点个数
- Count Complete Tree Nodes
- Swap Nodes in Pairs
- mac平台下面nodejs环境搭配
- Leetcode[19]-Remove Nth Node From End of List
- nodejs全局变量
- nodejs supervisor
- nodejs 运行
- leetcode 25 -- Reverse Nodes in k-Group
- inode、软连接、硬链接
- 让你的 Node.js 应用跑得更快的 10 个技巧(转)
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Count Complete Tree Nodes || LeetCode1