node.js :: introduction — part 2

30

Upload: roman-liutikov

Post on 02-Dec-2014

472 views

Category:

Technology


4 download

DESCRIPTION

Introduction to Node.js development. A brief talk about Node's API, frameworks & libs, use cases and prototyping.

TRANSCRIPT

Page 1: Node.js :: Introduction — Part 2
Page 2: Node.js :: Introduction — Part 2

PLANNode.jsFrameworks&LibsDemoapplication

Page 3: Node.js :: Introduction — Part 2

NODE.JSisbadfor:

CPUheavytasksDoingeverythingwithNode

Page 4: Node.js :: Introduction — Part 2

NODE.JSisgoodfor:

PrototypingREST/JSONAPIsSPAStreamingdataReal-timeapps

Page 5: Node.js :: Introduction — Part 2

MODULES

NodePackageManager

~55kmodulesavailable

Page 6: Node.js :: Introduction — Part 2

NPMnpminstallexpressnpminstallexpress-gnpminstallexpress--savenpminstallnodemon--save-dev

Page 7: Node.js :: Introduction — Part 2

PACKAGE.JSON{"name":"application-name","version":"0.0.1","private":true,"scripts":{"start":"nodeapp.js"},"dependencies":{"express":"3.4.8","jade":"*"},"devDependencies:{}}

npmpublish<tarball>npmpublish<folder>

Page 8: Node.js :: Introduction — Part 2

HTTPSERVERvarhttp=require('http');

http.createServer(function(req,res){res.writeHead(200,{'Content-Type':'text/plain'});res.end('HelloWorld!');}).listen(3000);

nodeserver.js

Page 9: Node.js :: Introduction — Part 2

WHAT'SINSIDEHTTP,HTTPS&TCPinterfacesFileSystemI/OStreamsChildProcessCluster...

Page 10: Node.js :: Introduction — Part 2

NETWORKINTERFACESHTTP/HTTPS/TCP

//requireamodule

varserver=http||https||net;

server.createServer([requestListener]).listen(port,[callback]);

Page 11: Node.js :: Introduction — Part 2

FILESYSTEMI/Ovarfs=require('fs');

fs.readFile(filename,[options],callback);fs.readFileSync(filename,[options]);

fs.writeFile(filename,data,[options],callback);fs.writeFileSync(filename,data,[options]);

fs.rmdir(path,callback);fs.unlink(path,callback);fs.readdir(path,callback);

Page 12: Node.js :: Introduction — Part 2

STREAMSReadable(req,fs,stdout,stderr)Writable(res,fs,stdin)Duplex(TCPsockets,crypto)Transform(zlib,crypto)

Page 13: Node.js :: Introduction — Part 2

STREAMSUSECASEhttp.createServer(function(req,res){fs.readFile(__dirname+'/file.txt',function(err,data){res.end(data);});});

VShttp.createServer(function(req,res){varstream=fs.createReadStream(__dirname+'/file.txt');stream.pipe(res);});

Page 14: Node.js :: Introduction — Part 2

CHILDPROCESSvarcp=require('child_process');cp.spawn(command,[args],[options]);cp.exec(command,[options],callback);cp.execFile(file,[args],[options],[callback]);cp.fork(modulePath,[args],[options]);

child.stdin//Writablestreamchild.stdout//Readablestreamchild.stderr//Readablestream

//Sync,usedwith'forked'processonlychild.send(message);child.on('message',callback);

Page 15: Node.js :: Introduction — Part 2

CLUSTERvarcluster=require('cluster'),http=require('http'),numCPUs=require('os').cpus().length;

if(cluster.isMaster){for(vari=0;i<numCPUs;i++){cluster.fork();}}else{http.createServer(function(req,res){res.writeHead(200,{'Content-Type':'text/plain'});res.end('HelloWorld!');}).listen(3000);}

Page 16: Node.js :: Introduction — Part 2

PROTOTYPINGMEANSTACK

MongoDB+Express+AngularJS+Node.js

mean.io

Page 17: Node.js :: Introduction — Part 2

EXPRESSMiddlewaresystemRouterTemplating(Jade,EJS)

npminstall-gexpressexpressappname

Page 18: Node.js :: Introduction — Part 2

SETTINGUPvarexpress=require('express'),app=express();

app.set('port',process.env.PORT||3000);app.set('viewengine','jade');app.set('views',__dirname+'/views');

app.use(express.bodyParser());app.use(express.methodOverride());app.use(app.router);app.use(express.static(path.join(__dirname,'public')));

app.listen(app.get('port'));

Page 19: Node.js :: Introduction — Part 2

MIDDLEWARESapp.use(function(req,res,next){//Dosomething...next();//Callnextmiddleware});

varmiddleware=function(req,res,next){//Dosomething...next();//Callnextmiddleware};

Page 20: Node.js :: Introduction — Part 2

ROUTESapp.get('/',function(req,res){res.render('index');});

app.get('/user',middleware,function(req,res){res.render('user');//Renderpageforauthorizedusersonly});

Page 21: Node.js :: Introduction — Part 2

ERRORHANDLINGCUSTOMERRORS

varAuthError=function(msg){Error.call(this);Error.captureStackTrace(this,arguments.callee);this.message=msg;this.name='AuthError';};

AuthError.prototype.__proto__=Error.prototype;

Page 22: Node.js :: Introduction — Part 2

ERRORHANDLINGERRORMIDDLEWARE

app.use(function(err,req,res,next){if(err.name=='AuthError'){res.send(401,{error:err.message});}});

varmiddleware=function(req,res,next){if(req.body.password!='password'){returnnext(newAuthError('Unauthorized'));}next();};

Page 23: Node.js :: Introduction — Part 2

MONGODBDocument-OrientedBSONdatastorage

+MongooseODM

varmongoose=require('mongoose');

mongoose.connect('mongodb://localhost/dbname');

Page 24: Node.js :: Introduction — Part 2

MONGOOSESCHEMASvarSchema=require('mongoose').Schema;

varUserSchema=newSchema({username:{type:String,unique:true,required:true},comments:[{body:String,date:Date}],modified:{type:Date,default:Date.now},role:String});varUser=mongoose.model('User',UserSchema);

Page 25: Node.js :: Introduction — Part 2

CRUDvaruser=newUser(data);user.save(function(err,user){});User.find(function(err,users){});User.find({role:'Moderator'},function(err,users){});User.findOne({username:'user'},function(err,user){});User.findById(id,function(err,user){user.remove(function(err){});});

Page 26: Node.js :: Introduction — Part 2

JSON/RESTAPIapp.post('/books',function(req,res,next){varbook=newBook(req.body);book.save(function(err,book){if(err)returnnext(newError('Servererror'));res.send(200,{book:book});});});app.get('/books/:id',function(req,res,next){Book.findById(req.params.id,function(err,book){if(err)returnnext(newError('Servererror'));if(!book)returnres.send(404,{error:'Notfound'});res.send(200,{book:book});});});//...

Page 27: Node.js :: Introduction — Part 2

REAL-TIMESOCKET.IO

vario=require('socket.io').listen(80);io.sockets.on('connection',function(socket){socket.on('myevent',function(data){});socket.emit('anotherevent',data);});

Page 28: Node.js :: Introduction — Part 2

DEMOTIME

Page 29: Node.js :: Introduction — Part 2

WHATELSE?ForeverNodemonNode-InspectMeteorJXcoreCLIFront-endtools

Page 30: Node.js :: Introduction — Part 2

LINKSnodejs.org/apigithub.com/substack/stream-handbooknodestreams.comhowtonode.orgnodeschool.iogithub.com/roman01la/RTVideo