码迷,mamicode.com
首页 > Web开发 > 详细

nodejs入门学习

时间:2014-12-23 18:57:22      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

基础

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;

 

nodejs入门学习

标签:

原文地址:http://www.cnblogs.com/feilv/p/4180572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!