nodejs入門學習

來源:互聯網
上載者:User

標籤:

基礎

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入門學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.