nodejs基本点

一、require方法和exports对象

看下面的小例子
student.js

function add(student)
{
    console.log("add student:"+student);
}
exports.add = add;

teacher.js

function add(teacher)
{
    console.log("add teacher:"+teacher);
}
exports.add = add;

clazz.js

var student = require("./student");
var teacher = require("./teacher");

function add(teacherName, students)
{
    teacher.add(teacherName);
    students.forEach(function(item, index){
        student.add(item);
    });
}
exports.add = add

test.js

var kclazz = require('./clazz');

kclazz.add("chm",['张三','李四','王五']);

关于require和exports以及exports和module.exports的知识在前面的文章html5 web相关有详细介绍。

http模块的request方法

下面是使用request方法给博客提交一个评论。注意,这里大家不要恶意灌水,否则账号可能被封。
自己给我博客下面的Android后台优化文章提交了一条测试评论。

var http = require("http");
var querystring =require("querystring");

//对象序列化成字符串
var postData = querystring.stringify({
    'content':'一条测试评论!',
    'commentid':'',
    'replyId':''
});

var options = {
    hostname: 'blog.youkuaiyun.com',
    port: 80,
    path:'/zxc123w/comment/submit?id=52712831',
    search: '?id=52712831',
    method: 'POST',
    headers: {
        'Accept':'*/*',
        'Accept-Encoding':'gzip, deflate',
        'Accept-Language':'zh-CN,zh;q=0.8',
        'Connection':'keep-alive',
        'Content-Length':postData.length,
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie':'bdshare_firstime=1474697719513; uuid_tt_dd=5967015093691172370_20160924; __message_district_code=330000; uuid=78c9be2e-5a6a-49b6-9b23-94cdb094e6cc; _gat=1; _ga=GA1.2.1990464495.1474710983; UserName=zxc123ew; UserInfo=%2BvvgYFMdtmXUKWYiF7BxXMuv166qvkztqA21%2FFo2wE5I8H9CQjTYoVq6p%2BS94uFGvMsYWRMEQRqOeEIzfI3inipUewoOH60%2FJ%2BNYURIQScSW2f5NKnUFJbemvtxrzu2h; UserNick=xxx; AU=FF9; UN=xxx; UE="xxx"; BT=1476083848179; access-token=83a6317a-10bf-4979-9fd2-745e61416494; avh=52712831; dc_tos=oetlqi; __message_sys_msg_id=0; __message_gu_msg_id=0; __message_cnel_msg_id=0; __message_in_school=0; dc_session_id=1476083845706',
        'Host':'blog.youkuaiyun.com',
        'Origin':'http://blog.youkuaiyun.com',
        'Referer':'http://blog.youkuaiyun.com/zxc123e/article/details/52712831',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
        'X-Requested-With':'XMLHttpRequest'
    }
};

var req = http.request(options, function(res){
    console.log('Status: '+res.statusCode);
    console.log('headers: '+JSON.stringify(res.headers));
    res.on("data", function(chunk){
        console.log(Buffer.isBuffer(chunk));
    })
    res.on('end', function(){
        console.log("评论完毕");
    })
});
req.on("error", function(e){
    console.log('Error: '+e.message);
});
req.write(postData);
req.end();

代码里面我修改了cookie的一些信息,但是还要再次提醒大家不要恶意灌水。

EventEmitter类

events 模块只提供了一个对象: events.EventEmitter。EventEmitter 的核心就是事件触发与事件监听器功能的封装。Node.js里面的许多对象都会分发事件:一个net.Server对象会在每次有新连接时分发一个事件, 一个fs.readStream对象会在文件被打开的时候发出一个事件。 所有这些产生事件的对象都是 events.EventEmitter 的实例。

var events = require("events");

var server = new events.EventEmitter();

//默认情况下, EventEmitters 如果你添加的监听器超过 10 个就会输出警告信息。 setMaxListeners 函数用于提高监听器的默认限制的数量。
setMaxListeners(11)

server.on('say', function(who){
    console.log(who+" say hello");
});

server.on('say', function(who){
    console.log(who+" say 伐木累!");
})
server.on('eat', function(who){
    console.log(who+" 吃饭");
});
server.emit('say', 'he');

var callback = function(stream) {
  console.log('someone connected!');
};
server.on('connection', callback);
server.removeListener('connection', callback);
server.emit('connection');
console.log(events.EventEmitter.listenerCount(server, 'say'));

Stream和Buffer

Stream(流)

Stream 是一个抽象接口,Node 中有很多对象实现了这个接口。例如,对http 服务器发起请求的request 对象就是一个 Stream,还有stdout(标准输出)。

Node.js,Stream 有四种流类型:

  • Readable - 可读操作。
  • Writable - 可写操作。
  • Duplex - 可读可写操作.
  • Transform - 操作被写入数据,然后读出结果。

所有的 Stream 对象都是 EventEmitter 的实例。常用的事件有:

  • data - 当有数据可读时触发。
  • end - 没有更多的数据可读时触发。
  • error - 在接收和写入过程中发生错误时触发。
  • finish - 所有数据已被写入到底层系统时触发。

Buffer(缓冲区)

Buffer 类是随 Node 内核一起发布的核心库。Buffer 库为 Node.js 带来了一种存储原始数据的方法,可以让 Node.js 处理二进制数据,每当需要在 Node.js 中处理I/O操作中移动的数据时,就有可能使用 Buffer 库。一个 Buffer 类似于一个整数数组,但它对应于 V8 堆内存之外的一块原始内存。

Promise

nodejs的最大的优点是高并发,适合适合I/O密集型应用。但是这带来的问题是异步操作和函数回调,你会需要在一个动作完成之后继续做别的动作,因此回调会不断的嵌套。你会发现很快这些代码就很难阅读了,更别提维护了。于是,Promise应运而生。Promise表示一个异步操作的最终结果。与Promise最主要的交互方法是通过将函数传入它的then方法从而获取得Promise最终的值或Promise最终最拒绝(reject)的原因。

下面是一个页面上三个小球移动的动画效果。

<!DOCTYPE html>
<html>
<head>
    <title>Promise</title>

<style type="text/css">
    .ball {
        width: 40px;
        height: 40px;
        border-radius: 20px;
    }
    .ball1 {
        background-color: red;
    }
    .ball2 {
        background-color: yellow;
    }
    .ball3 {
        background-color: green;
    }
</style>
<script type="text/javascript" src="../node_modules/bluebird/js/browser/bluebird.js"></script>
</head>
<body>
    <div class="ball ball1" style="margin-left: 0;"></div>
    <div class="ball ball2" style="margin-left: 0;"></div>
    <div class="ball ball3" style="margin-left: 0;"></div>

    <script type="text/javascript">
        var ball1 = document.querySelector('.ball1');
        var ball2 = document.querySelector('.ball2');
        var ball3 = document.querySelector('.ball3');
        /*function animate(ball, distance, cb)
        {
            setTimeout(function(){
                var marginLeft = parseInt(ball.style.marginLeft, 10);
                if (marginLeft === distance) {
                    cb&&cb();
                }else{
                    if (marginLeft < distance)
                    {
                        marginLeft++;
                    }else{
                        marginLeft--;
                    }
                    ball.style.marginLeft = marginLeft+'px';
                    animate(ball, distance, cb);
                }


            }, 13);
        }
        animate(ball1, 100, function(){
            animate(ball2,200, function(){
                animate(ball3, 300, function(){
                    animate(ball3, 150, function(){
                        animate(ball2,150, function(){
                            animate(ball1,150, function(){
                            });
                        });
                    });
                });
            });
        });*/
        var Promise = window.Promise;
        function promiseAnimate(ball, distance)
        {
            return new Promise(function(resolve, reject){
                function _animate()
                {
                    setTimeout(function(){
                        var marginLeft = parseInt(ball.style.marginLeft, 10);
                        if (marginLeft === distance) {
                            resolve();
                            return;
                        }else{
                            if (marginLeft < distance)
                            {
                                marginLeft++;
                            }else{
                                marginLeft--;
                            }
                            ball.style.marginLeft = marginLeft+'px';
                            _animate();
                        }

                    }, 13);
                }
                //第一次启动
                _animate();
            });
        }
        promiseAnimate(ball1, 100)
            .then(function(){
                return promiseAnimate(ball2, 200);
            })
            .then(function(){
                return promiseAnimate(ball3, 300);
            })
            .then(function(){
                return promiseAnimate(ball3, 150);
            })
            .then(function(){
                return promiseAnimate(ball2, 150);
            })
            .then(function(){
                return promiseAnimate(ball1, 150);
            });
    </script>
</body>
</html>

promise是一个标准,它描述了异步调用的返回结果,包括正确返回结果和错误处理。关于详细的说明文档可以参考 Promises/A+ 。目前实现 promise 标准的模块有很多,如 Q 、 bluebird 和 Deferred。这里我们使用的bluebird。新版nodejs中也有这个模块。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值