Giới thiệu ngắn về Nodejs và ứng dụng realtime.
INTRO TO NODE.JS- LEVEL ONE - INTRO TO NODE.JSWHAT IS NODE.JS?It’s fast because it’s mostly C codeAllows you to build scalable network applications using JavaScript on the server-side.V8 JavaScript RuntimeNode.js INTRO TO NODE.JSWHAT COULD YOU BUILD?•Websocket Server•Fast File Upload Client•Ad Server•Any Real-Time Data AppsLike a chat server INTRO TO NODE.JSWHAT IS NODE.JS NOT?•A Web Framework•For BeginnersIt’s very low level•Multi-threaded You can think of it as a single threaded server INTRO TO NODE.JSOBJECTIVE: PRINT FILE CONTENTSThis is a “Callback”Read file from Filesystem, set equal to “contents”Print contents•Blocking Code•Non-Blocking CodeDo something elseRead file from Filesystemwhenever you’re complete, print the contentsDo Something else console.log(contents);INTRO TO NODE.JSBLOCKING VS NON-BLOCKINGvar contents = fs.readFileSync('/etc/hosts');console.log(contents);console.log('Doing something else');•Blocking Code•Non-Blocking Codeconsole.log('Doing something else');Stop process until completefs.readFile('/etc/hosts', function(err, contents) {}); fs.readFile('/etc/hosts', function(err, contents) {console.log(contents);});INTRO TO NODE.JSCALLBACK ALTERNATE SYNTAXvar callback = function(err, contents) { console.log(contents);}fs.readFile('/etc/hosts', callback);Same as INTRO TO NODE.JSBLOCKING VS NON-BLOCKINGblocking0snon-blocking10s5s0s 10s5sfs.readFile('/etc/hosts', callback);fs.readFile('/etc/inetcfg', callback);var callback = function(err, contents) { console.log(contents);} hello.js NODE.JS HELLO DOG$ curl http://localhost:8080Hello, this is dog.How we require modulesStatus code in headerResponse bodyClose the connectionListen for connections on this port $ node hello.jsRun the servervar http = require('http');http.createServer(function(request, response) {response.writeHead(200);response.write("Hello, this is dog.");response.end();}).listen(8080);console.log('Listening on port 8080 .');Listening on port 8080 . [...]... attach function(request, response){ } When ‘request’ event is emitted EVENTS request event HTTP ECHO SERVER http.createServer(function(request, response){ }); But what is really going on here? http:/ /nodejs. org/api/ EVENTS BREAKING IT DOWN http.createServer(function(request, response){ }); EVENTS ALTERNATE SYNTAX http.createServer(function(request, response){ }); Same as var server = http.createServer(); 123doc.vn