nodejs入门学习

基础

node.js是用c++编写的一个javascript运行环境,特点:事件驱动、异步I/0。作为服务器端的javascript解释器,Node是一个轻量高效的开发平台,用户构建响应快速、高度可扩展的web应用,它使用事件驱动和非阻塞的I/O模型,非常适合开发数据密集、对实时响应要求高的分布式应用。

server.js //简单的http服务器

var http = require(‘http‘);
http.createServer(function(req, res) {
    res.writeHead(200, {‘Content-Type‘: ‘text/plain‘});
    res.end(‘hello world\n‘);
}).listen(8888);
console.log(‘server running at http://127.0.0.1‘);

执行:node server.js

模块

main.js

var hello = require(‘./hello‘);
hello.world();

hello.js

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

main1.js

var Hello = require(‘./hello1‘);
hello = new Hello();
hello.setName(‘aaa‘);
hello.sayHello();

hello1.js

function Hello() {
    var name;
    this.setName = function(myname) {
        name = myname;
    }
    this.sayHello = function() {
        console.log(‘hello ‘ + name);
    }
}
module.exports = Hello;

事件

event.js

var EventEmitter = require(‘events‘).EventEmitter;
var event = new EventEmitter();
event.on(‘event1‘, function() {
    console.log(‘event1 occured.‘);
});
setTimeout(function() {
    event.emit(‘event1‘);
}, 1000);

event1.js

var events = require(‘events‘);
var emitter = new events.EventEmitter();
emitter.on(‘event1‘, function(arg1, arg2) {
    console.log(‘listener1‘, arg1, arg2);
});
emitter.on(‘event1‘, function(arg1, arg2) {
    console.log(‘listener2‘, arg1, arg2);
});
emitter.emit(‘event1‘, ‘aaa‘, 123);

更多参考http://www.w3cschool.cc/nodejs/nodejs-event.html

路由

index.js

var server = require(‘./server‘);
var router = require(‘./router‘);
server.start(router.route);

server.js

var http = require(‘http‘);
var url = require(‘url‘);
function start(route) {
    function onRequest(req, res) {
        var pathname = url.parse(req.url).pathname;
        console.log(‘request for ‘ + pathname + ‘ received.‘);
        route(pathname);
        res.writeHead(200, {‘Conten-Type‘: ‘text/plain‘});
        res.write(‘hello, world‘);
        res.end();
    }
    http.createServer(onRequest).listen(8888);
    console.log(‘server has started.‘);
}
exports.start = start;

router.js

function route(pathname) {
    console.log(‘about to route a request for ‘ + pathname);
}
exports.route = route;

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。