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(port, hostname, backlog, callback);
- 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