mime.json
{ ".323": "text/h323", ".3gp": "video/3gpp", ".aab": "application/x-authoware-bin", ".zip": "application/zip", ".json": "application/json"}
异步执行顺序
异步的方法,会等到同步处理完后,才开始执行
var fs = require('fs');console.log('1')function getMime(){ fs.readFile('mime.json',function(err,data){ console.log(data.toString()) console.log('2') })}console.log('3')getMime()
非阻塞io
直接调用,拿不到异步方法,请求的数据
function getMime(){ fs.readFile('mime.json',function(err,data){ return data; })}console.log(getMime()) //underfind
回调函数
var fs = require('fs');function getMime(callback){ fs.readFile('mime.json',function(err,data){ callback(data); })}getMime(function(result){ console.log(result.toString())})
node.js 事件驱动
最简单的事件驱动
var events = require('events');var EventEmitter = new events.EventEmitter();EventEmitter.on('to_mime', function (data) { console.log(data); //给mime发送的数据})EventEmitter.emit('to_mime', '给mime发送的数据')
事件驱动里有事件驱动
var events = require('events');var EventEmitter = new events.EventEmitter();EventEmitter.on('to_mime', function (data) { console.log(data);})EventEmitter.on('to_parent',function(data){ console.log(data); EventEmitter.emit('to_mime','给mime发送的数据')})setTimeout(function(){ console.log('开始广播...'); EventEmitter.emit('to_parent','发送的数据')},1000)
获取mime.json里的数据
var fs = require('fs');var events = require('events');var EventEmiter = new events.EventEmitter();function getMime(){ fs.readFile('mime.json',function(err,data){ EventEmiter.emit('data',data) })}getMime()EventEmiter.on('data',function(mime){ console.log(mime.toString())})