Download - Node.js :: Introduction — Part 2
![Page 1: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/1.jpg)
![Page 2: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/2.jpg)
PLANNode.jsFrameworks&LibsDemoapplication
![Page 3: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/3.jpg)
NODE.JSisbadfor:
CPUheavytasksDoingeverythingwithNode
![Page 4: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/4.jpg)
NODE.JSisgoodfor:
PrototypingREST/JSONAPIsSPAStreamingdataReal-timeapps
![Page 5: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/5.jpg)
MODULES
NodePackageManager
~55kmodulesavailable
![Page 6: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/6.jpg)
NPMnpminstallexpressnpminstallexpress-gnpminstallexpress--savenpminstallnodemon--save-dev
![Page 7: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/7.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/8.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/9.jpg)
WHAT'SINSIDEHTTP,HTTPS&TCPinterfacesFileSystemI/OStreamsChildProcessCluster...
![Page 10: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/10.jpg)
NETWORKINTERFACESHTTP/HTTPS/TCP
//requireamodule
varserver=http||https||net;
server.createServer([requestListener]).listen(port,[callback]);
![Page 11: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/11.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/12.jpg)
STREAMSReadable(req,fs,stdout,stderr)Writable(res,fs,stdin)Duplex(TCPsockets,crypto)Transform(zlib,crypto)
![Page 13: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/13.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/14.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/15.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/16.jpg)
PROTOTYPINGMEANSTACK
MongoDB+Express+AngularJS+Node.js
mean.io
![Page 17: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/17.jpg)
EXPRESSMiddlewaresystemRouterTemplating(Jade,EJS)
npminstall-gexpressexpressappname
![Page 18: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/18.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/19.jpg)
MIDDLEWARESapp.use(function(req,res,next){//Dosomething...next();//Callnextmiddleware});
varmiddleware=function(req,res,next){//Dosomething...next();//Callnextmiddleware};
![Page 20: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/20.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/21.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/22.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/23.jpg)
MONGODBDocument-OrientedBSONdatastorage
+MongooseODM
varmongoose=require('mongoose');
mongoose.connect('mongodb://localhost/dbname');
![Page 24: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/24.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/25.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/26.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/27.jpg)
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](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/28.jpg)
DEMOTIME
![Page 29: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/29.jpg)
WHATELSE?ForeverNodemonNode-InspectMeteorJXcoreCLIFront-endtools
![Page 30: Node.js :: Introduction — Part 2](https://reader034.vdocument.in/reader034/viewer/2022042601/547ea5d75906b5ab718b46d6/html5/thumbnails/30.jpg)
LINKSnodejs.org/apigithub.com/substack/stream-handbooknodestreams.comhowtonode.orgnodeschool.iogithub.com/roman01la/RTVideo