Node.js
Features
The Read-Eval-Print-Loop
Single line
Multi line
$ node
> var foo = "Hello World!";
undefined
> foo;
'Hello World!'
> console.log(foo);
Hello World!
undefined
> for (var i = 0; i < 3; i++) {
... console.log(i);
... }
0
1
2
undefined
.save filename
.editor
Modules
npm
npm install commander@1.0.x
npm install commander@"~1.1.0"
https://www.npmjs.com/
Where they come from
Where they are placed
global vs local
npm root
npm root -g
npm ls [--depth]
npm ls -g
npm outdated
npm update
The require() Function
Modules resolved by path
Modules resolved by name
require.resolve("http");
function requireUncached(module){
delete require.cache[require.resolve(module)]
return require(module)
}
CommonJS vs ES6
require resolution
node_modules
package.json
basic structure, deps, scripts
npm repo [package name]
Patterns
Callbacks (async call with process.nextTick)
Event Emitter (Observable)
Promises
Event emitter
mechanism for tracking state changes
Consuming events
emitter.on(eventName, listener)
server.on('connection', (stream) => {
console.log('someone connected!');
});
Creating event emitter
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
ES6
var EventEmitter = require('events');
var inherits = require('util').inherits;
function MyEmitter() {
EventEmitter.call(this);
}
inherits(MyEmitter, EventEmitter);
ES5
Producing events
emitter.emit(eventName, listener)
const myEmitter = new MyEmitter();
myEmitter.on('event', (param1, param2) => {
console.log('an event occurred!', param1, param2);
// logs `an event occurred!,3,4`
});
myEmitter.emit('event', 3, 4);
Error handling
const myEmitter = new MyEmitter();
myEmitter.on('error', (error) => {
console.log('an error occurred!', error);
});
myEmitter.emit('error', {});
Catching in process
Catching in even temitter
const myEmitter = new MyEmitter();
process.on('uncaughtException', function(err) {
console.log('an error occured');
});
myEmitter.emit('error', {});
Streams
mechanism for working with objects that are a source or a target of data
Middleware
HTTP transaction
Create a listening server
var http = require('http');
var server = http.createServer(function(request, response) {
// server requests are processed here
});
since `server` is an instance of event emitter
var server = http.createServer();
server.on('request', function(request, response) {
// the same functionality can be implemented here
});
and start listening
server.listen(8543);
Obtain request details
const server = http.createServer(function (request, response) {
const headers = request.headers;
const method = request.method;
const url = request.url;
if (headers['user-agent'].includes('Chrome') && method === 'GET' && url.includes('say-hello')) {
response.write('Hello to Chrome!');
} else {
response.write('Unknown request!');
}
response.end();
});
Getting request body
const http = require('http');
const fs = require('fs');
const server = http.createServer(function (request, response) {
const method = request.method;
const url = request.url;
if (method === 'POST' && url.includes('write-file')) {
let body = [];
request.on('error', function (err) {
console.error(err);
}).on('data', function (chunk) {
body.push(chunk);
}).on('end', function () {
body = Buffer.concat(body).toString();
fs.writeFile("request-body.txt", body, (err) => {
if (err) {
response.statusCode = 500;
}
response.end();
});
});
} else {
response.statusCode = 404;
response.end();
}
});
server.listen(5155);
Setting response body
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer(function (request, response) {
const method = request.method;
const url = request.url;
if (method === 'GET') {
fs.readFile(path.join(__dirname, url.substr(1)), (error, data) => {
if (error) {
response.statusCode = 404;
} else {
response.write(data);
}
response.end();
});
} else {
response.statusCode = 404;
response.end();
}
});
server.listen(5155);
Using streams
const server = http.createServer(function (request, response) {
const method = request.method;
const url = request.url;
if (method === 'POST' && url.includes('write-file')) {
const file = fs.createWriteStream('request-body.txt');
request.pipe(file);
} else {
response.statusCode = 404;
response.end();
}
});
Reading request body
Writing to response body
const server = http.createServer(function (request, response) {
const method = request.method;
const url = request.url;
if (method === 'GET') {
const file = fs.createReadStream(url.substr(1));
file.pipe(response);
} else {
response.statusCode = 404;
response.end();
}
});
Node.js
By maximk
Node.js
- 598