Skip to content

Latest commit

 

History

History
105 lines (67 loc) · 1.49 KB

demos-day-one.md

File metadata and controls

105 lines (67 loc) · 1.49 KB

How to Node

Standard Libraries Demo

var http = require('http');

var server = http.createServer(function(request, response) {
    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    response.end('Hello world');
});

server.listen(3000);

console.log("Server listening on http://localhost:3000");

Open http://localhost:3000


Developing and Debugging Demo

> npm install -g node-inspector

> node-debug app.js

> npm install -g nodemon

> nodemon app.js


CommonJS modules Demo

Create a simple logger module and import it into our app.

logger.js

exports.info = function(msg) {
    console.log(new Date() + ': ' + msg);
};

exports.error = function(msg) {
    console.error(new Date() + ': ' + msg);
};

Then modify app.js:

var logger = require('./logger');

logger.info('Logging hello world');

Demo

When you want to export a instance factory you must use module.exports.

point.js

function Point(x, y) {
    this.x = x;
    this.y = y;
}

Point.prototype.print = function() {
    console.log(this.x + ', ' + this.y);
}

module.exports = Point;

app.js

var Point = require('./Point');

var point = new Point(25, 36);

point.print();

Async callbacks and error handling Demo

app.js

var fs = require('fs');

fs.readFile('/', function (err) {
    if(err) throw err;

    console.log('completed');
});