Node.js -- HTTP

basic es6 class

definition

class Note {
    constructor(key, title, body) {
        this._key = key;
        this._title = title;
        this._body = body;
    }
    get key() { return this._key; }
    get title() { return this._title; }
    set title(newTitle) { return this._title = newTitle; }
    get body() { return this._body; }
    set body(newBody) { return this._body = newBody; }
}

getter & setter methods in ES6

    get key() { return this._key; } // getter function definition
    set title(newTitle) { return this._title = newTitle; } // setter function definition
------------------------------------------------------------------------------
    const key = aNote.key; // using getter function
    aNote.title = "The Rain" // using setter function

new instance

aNote = new Note()

test whether a given object is of a certain class

if (anotherNote instanceof Note) {
    ... it's a Note, so act on it as a Note
}

declare a subclass

class LoveNote extends Note {...}

change a class name

class myNote extends Note {} // extend with an empty class body

EventEmitter

An object that gives notifications (events) at different points in its life cycle.

  • By emitting events that other code can receive

.emit()

this.emit('eventName', data1, data2, ..); 
  • set the event name in the 'eventName' param, all the event data follow
  • 'this' object extends EventEmitter class

.on()

Receives data and listens to the event. 

emitter.on('eventName', (data1, data2, ...theArgs) => { 
  // act on event 
}); 
  • 'emitter' object extends EventEmitter class
  • specify event name, then provide a callback function that takes data from the emitter.
    • use rest operator to capture all unspecified data in an array

HTTPServer

  • Node.js native HTTP protocol object

creating HTTP server object

import * as http from 'http';
const server = http.createServer();

listen to port

server.listen(porthostnamebacklogcallback);

  • listen to localhost, port 8124 
server.listen(8124, '127.0.0.1');

Events

Request

  • Fired any time an HTTP request arrives on the server
  • Takes a callback, params:
    • request: contains data from the web browser (client)
    • response: gather data to be sent back in the response
server.on('request', (req, res) => {...}

upgrade

  • Emitted each time a client requests an HTTP upgrade

clientError

  • If a client connection emits an 'error' event, it will be forwarded here
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值