学习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
- 学习nodejs——callback, async i/o
- nodejs学习--I/O
- 深入浅出NodeJS——异步I/O
- NodeJS学习笔记(一)——异步I/O的理解
- [读书笔记]深入浅出NodeJS——Node中的异步I/O
- NodeJs——文件I/O(一)
- NodeJs——文件I/O(二)
- Java学习—I/O
- Async I/O and Python
- Nodejs 异步 I/O
- nodejs-异步I/O
- NodeJS -- 异步I/O
- nodejs中的async模块学习
- Java学习—I/O概述
- python学习六—文件I/O
- nodejs之异步I/O
- NodeJS异步I/O解析
- ABout db file async I/O submit ?
- 搜狗输入法在输入框内无法正常使用
- 日经社説 20150611 海外買収のつまずきから学ぶ
- 黑马程序员--If-else和switch语句
- Eclipse常用插件在线安装和离线安装方式
- 九度OJ-题目1350:二叉树的深度
- 学习nodejs——callback, async i/o
- xloadtree实现web动态目录树(分层加载)
- 15个SAT数学高分公式介绍
- Python正则表达式
- 一篇读懂CSS布局模型
- Hangover
- windows下python画图matplotlib
- mysql ERROR 1025 (HY000): Error on rename of
- 日经社説 20150611 訪日外国人の増加へ規制緩和の加速を