node js 学习(2)回调函数 事件循环 buffer stream 模块系统

来源:互联网 发布:重庆seo网站诊断 编辑:程序博客网 时间:2024/04/30 16:08

node js的回调函数 node js的异步编程的直接体现就是回调,异步编程依托于回调来进行实践 node js的所有API都支持回调

我们可以在一边读取文件的同时 一边来进行其他的命令 这样可以提高效率

阻塞代码示例

var fs = require("fs");var data = fs.readFileSync("input.txt");console.log(data.toString());console.log("程序执行完毕");

飞阻塞代码 通过回调来实现

var fs = require("fs");fs.readFile("input.txt",function (err,data) {    if(err)        return console.log(err);    console.log(data.toString());})console.log("程序执行结束")

事件循环 node js是单进程单线程应用支持 但是通过事件和回调支持并发,

类似于观察者模式,事件相当于一个主题,而所有注册到这个事件上的处理函数相当于观察者

//引入events模块var events = require("events");//创建eventEmitter对象var eventEmitter = new events.EventEmitter();//创建事件处理程序var connectHandler = function connected() {    console.log("链接成功");//触发data_received事件    eventEmitter.emit("data_received");}//绑定connection事件处理程序eventEmitter.on("connection",connectHandler);//使用匿名函数绑定 data_received 事件eventEmitter.on('data_received', function(){    console.log('数据接收成功。');});// 触发 connection 事件eventEmitter.emit('connection');console.log("程序执行完毕。");

emit表示触发事件on表示指定事件

首先触发connection事件 connection事件绑定了connectHandler函数 因此执行connectHandler函数 随后在函数中他又触发了data_received事件 data_received通过匿名函数形式绑定了函数 就是这样一个流程

node js所有的异步I/O 操作在完成时都会放一个事件到事件队列中 所有这些产生事件的对象都是event.EventEmitter的实例

js本身是只有字符串数据类型的 没有二进制数据类型 定义了一个buffer 该类用来创建一个数据的缓存区

写入缓存区 返回实际写入的大小

var buf = new Buffer(256);var len = buf.write("www.baidu.com");console.log(len);
从流中读取模块;相当于对于文件的操作 这里不展开


node js的模块系统  可以说 模块和文件是意义对应的 可以通过require来引入外面的模块随后 调用他的函数

node js提供了exports和require两个对象 exports是模块公开的接口 require 用于从外部获取一个模块的接口 即所获取模块的exports对象

hello.js中的文件内容如下

exports.helloWorld = function () {    console.log("hello world");}

index.js通过./hello 来获取hello.js的实例

var hello = require("./hello");hello.helloWorld();
封装到对象中

function Hello() {    var name;    this.setName = function(thyName) {        name = thyName;    };    this.sayHello = function() {        console.log('Hello ' + name);    };    this.saHello = function () {        console.log("Hi");    }};module.exports = Hello;
进行调用 通过实例化进行调用

var Hello = require('./hello');hello = new Hello();hello.setName('BYVoid');hello.saHello();






0 0
原创粉丝点击