learnyounode是NodeSchool里介绍基本异步编程的课程,通过13个简单的练习可以学习异步io,http等知识。运行此课程使用如下命令
npm install -g learnyounode #安装
learnyounode 运行为方便以后复习,现将每一个练习的代码整理如下
hello_world(你好,世界)
console.log("HELLO WORLD")
baby_steps(婴儿学步)
//此例子演示从命令行接受参数的方法var result = 0 //process.argv[0]是node,process.argv[1]是脚本文件名,所以从2开始才是输入参数 for (var i = 2; i < process.argv.length; i++) result += Number(process.argv[i]) console.log(result)
my_first_io(第一个 I/O)
var fs = require('fs') //使用同步的方式读取文件,返回值是一个Buffer对象var contents = fs.readFileSync(process.argv[2]) var lines = contents.toString().split('\n').length - 1 console.log(lines)
my_first_async_io(第一个异步 I/O)
var fs = require('fs') var file = process.argv[2] fs.readFile(file, function (err, contents) { // fs.readFile(file, 'utf8', callback) can also be used var lines = contents.toString().split('\n').length - 1 console.log(lines) })
filtered_ls(LS 过滤器)
var fs = require('fs') var path = require('path')//异步的方式读取目录文件,详情http://nodejs.org/api/fs.html#fs_fs_readdir_path_callback
fs.readdir(process.argv[2], function (err, list) { list.forEach(function (file) { if (path.extname(file) === '.' + process.argv[3]) console.log(file) }) })
make_it_modular(使其模块化)
solution.js
var filterFn = require('./solution_filter.js') var dir = process.argv[2] var filterStr = process.argv[3] filterFn(dir, filterStr, function (err, list) { if (err) return console.error('There was an error:', err) list.forEach(function (file) { console.log(file) }) })
solution_filter.js
var fs = require('fs') var path = require('path') module.exports = function (dir, filterStr, callback) { fs.readdir(dir, function (err, list) { if (err) return callback(err) list = list.filter(function (file) { return path.extname(file) === '.' + filterStr }) callback(null, list) }) }
http_client(HTTP 客户端)
var http = require('http') //http://nodejs.org/api/http.html#http_http_get_options_callback http.get(process.argv[2], function (response) { response.setEncoding('utf8') response.on('data', console.log) response.on('error', console.error) })
http_collect(HTTP 收集器)
//运行此例子需要安装bl
// npm install bl
var http = require('http') var bl = require('bl') http.get(process.argv[2], function (response) { response.pipe(bl(function (err, data) { if (err) return console.error(err) data = data.toString() console.log(data.length) console.log(data) })) })
juggling_async(玩转异步)
var http = require('http') var bl = require('bl') var results = [] var count = 0 function printResults () { for (var i = 0; i < 3; i++) console.log(results[i]) } function httpGet (index) { http.get(process.argv[2 + index], function (response) { response.pipe(bl(function (err, data) { if (err) return console.error(err) results[index] = data.toString() count++ if (count == 3) printResults() })) }) } for (var i = 0; i < 3; i++) httpGet(i)
time_server(授时服务器)
var net = require('net') function zeroFill(i) { return (i < 10 ? '0' : '') + i } function now () { var d = new Date() return d.getFullYear() + '-' + zeroFill(d.getMonth() + 1) + '-' + zeroFill(d.getDate()) + ' ' + zeroFill(d.getHours()) + ':' + zeroFill(d.getMinutes()) } var server = net.createServer(function (socket) { socket.end(now() + '\n') }) server.listen(Number(process.argv[2]))
http_file_server(HTTP 文件服务器)
var http = require('http') var fs = require('fs') var server = http.createServer(function (req, res) { res.writeHead(200, { 'content-type': 'text/plain' }) fs.createReadStream(process.argv[3]).pipe(res) }) server.listen(Number(process.argv[2]))
HTTP 大写转换器(HTTP 大写转换器)
var http = require('http') var map = require('through2-map') var server = http.createServer(function (req, res) { if (req.method != 'POST') return res.end('send me a POST\n') req.pipe(map(function (chunk) { return chunk.toString().toUpperCase() })).pipe(res) }) server.listen(Number(process.argv[2]))
http_json_api_server(HTTP JSON API 服务器)
var http = require('http') var url = require('url') function parsetime (time) { return { hour: time.getHours(), minute: time.getMinutes(), second: time.getSeconds() } } function unixtime (time) { return { unixtime : time.getTime() } } var server = http.createServer(function (req, res) { var parsedUrl = url.parse(req.url, true) var time = new Date(parsedUrl.query.iso) var result if (/^\/api\/parsetime/.test(req.url)) result = parsetime(time) else if (/^\/api\/unixtime/.test(req.url)) result = unixtime(time) if (result) { res.writeHead(200, { 'Content-Type': 'application/json' }) res.end(JSON.stringify(result)) } else { res.writeHead(404) res.end() } }) server.listen(Number(process.argv[2]))