Share
Embed
Node.js Fundamentals
Slides for Academy X's Node.js Fundamentals class.
http://www.academyx.com/training/san_francisco/javascript/node.js/
Matt Farmer
February 19, 2016
Transcript
46 slides
-
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 2/46 ABOUT ME Matt Farmer Traveled
to Europe for EMC to train people on hard drive failures Gained a passion for IO 2009 - 2014 - Director of Technology for UseAllFive Attended Node.js camp in 2010 2015 - CTO of GoFormative.com Created multi-threaded WebSocket to RESTful API bridge -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 3/46 WHAT WE WILL LEARN Intro
to Javascript How to install Node, and 3rd party libraries Create a basic HTTP server Build our first Express.js application Use Socket.io to create a Chat server INTRO TO JAVASCRIPT -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 4/46 INTRO TO JAVASCRIPT HISTORY Dominate
language used for dynamic content on the web Created in 1995 Primarily in browser until Node.js - 2009 -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 5/46 DETAILS Small language Protypical (not
classical) Language Very quirky - 1096 Pages - 176 pages JavaScript: The Definitive Guide JavaScript: The Good Parts The Good Parts @ Google 2009 The Better Parts @ JSConfUY 2014 -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 6/46 LANGUAGE FEATURES - VARIABLES Traditional
defined with the var keyword Has many confusing properties, like ES6 added: let: like var but without hoisting and block scoped const: like let but can only be assigned once variable hoisting -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 7/46 LANGUAGE FEATURES - VARIABLES console.log(varVariable);
// Undefined -- no error console.log(letVariable); // ReferenceError: letVariable is not defined console.log(constVariable); // ReferenceError: constVariable is not defined var varVariable = 'v'; let letVariable = 'l'; const constVariable = { 'name': 'c' }; // Watch out! This is works! constVariable.favoriteLanguage = 'javascript'; constVariable = 'another string'; //TypeError: Assignment to constant variable. -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 8/46 LANGUAGE FEATURES - ARRAYS let
myArray = [ 'one', 'two', ]; myArray.push('three'); // Push an item onto the end of a list myArray.unshift('zero'); // Push an item onto the front of a list console.log(myArray.pop()); // Return the last item in the list, and remove it console.log(myArray.shift()); // Return the first item in the list, and remove it -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 9/46 There are many other useful
methods, including: LANGUAGE FEATURES - ARRAYS - Join two arrays - Test if all elements pass a condition - Return a new array only elements that pass function - Loop over all elements in array - Join all elements of an array into a string - Creates a new array with the results of the provided function - Reduce it to a single value - Sort an array in place [].concat [].every [].filter [].forEach [].join [].map [].reduce [].sort -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 10/46 LANGUAGE FEATURES - OBJECTS let
myObject = { a: 'value', b: function() { console.log('do something'); }, }; myObject.a = 'new value'; let key = 'a'; myObject[key] = 'value set via dynamic key'; -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 11/46 LANGUAGE FEATURES - FUNCTIONS function
fnName(parameter1, parameter2, parameter3) { // code to be executed } First class - just like any other variable Can be: constructed during the execution of a program stored in data structures passed as arguments to other functions returned as the values of other functions -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 12/46 LANGUAGE FEATURES - CLOSURE A
closure is an inner function that has access to the outer (enclosing) function's variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables. -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 13/46 LANGUAGE FEATURES - CLOSURE function
carFactory(make) { function getMake() { return make; } function setMake(newMake) { make = newMake; } var publicMethods = { "getMake": getMake, "setMake": setMake, }; return publicMethods; } var ford = carFactory('ford'); console.log(ford.getMake()); // ford ford.setMake('honda'); console.log(ford.getMake()); // honda -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 14/46 WORKSHOP TIME! To run the
workshop, simply type the following: npm install --global javascripting javascripting ( provided by ) http://nodeschool.io CORE NODE.JS MODULES -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 15/46 CORE NODE.JS MODULES Learn more
at: HTTP let http = require('http'); const PORT = 3000; http.createServer(function (req, res) { // handle request }).listen(PORT); http://nodejs.org/api/http.html#http_http -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 16/46 Learn more at: QUERYSTRING let
querystring = require('querystring'); let str = querystring.stringify({ practical: 'node', lang: 'js', }); console.log(str); // practical=node&lang=js let params = querystring.parse('param1=a¶m2=b'); console.log(params); // { param1: 'a', param2: 'b' } http://nodejs.org/api/querystring.html -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 17/46 Learn more at: URL let
url = require('url'); let parts = url.parse('http://user:[email protected]:8080/p/a/t/h?query=string¶m2=two#hash'); console.log(parts); // Url { // protocol: 'http:', slashes: true, // auth: 'user:pass', host: 'host.com:8080', // port: '8080', hostname: 'host.com', // hash: '#hash', search: '?query=string¶m2=two', // query: 'query=string¶m2=two', // pathname: '/p/a/t/h', path: '/p/a/t/h?query=string¶m2=two', // href: 'http://user:[email protected]:8080/p/a/t/h?query=string¶m2=two#hash' // } http://nodejs.org/api/url.html -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 18/46 Learn more at: FS let
fs = require('fs'); let fileName = 'message.txt'; let contents = 'Hello\nWorld!'; fs.writeFile(fileName, contents, function (err) { if (err) throw err; console.log('Writing is done.'); }); fs.readFile(fileName, function (err, data) { if (err) throw err; console.log(data.toString()); }); http://nodejs.org/api/fs.html -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 19/46 Learn more at: FS (STREAMS)
let fs = require('fs'); let fileName = 'message.txt'; fs.createReadStream(fileName).pipe(process.stdout); http://nodeschool.io/#streamadventure -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 21/46 INSTALLING NODE Requirement: be able
to install multiple versions at once Many solutions exist - Built by the creator of NPM - Like Ruby's `rvm` command - Created by tj (a prolific Node.js contributor) Nave NVM N -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 22/46 NPM npm init Creates a
package.json file npm install Install packages already listed in a projects's package.json file into a node_modules folder npm install --save <package name> and npm install --save-dev <package name> Add a dependency to your package.json Git considerations Add node_modules to your .gitignore file. We don't want to check in other people's code into our project -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 23/46 PACKAGE.JSON FILE name - the
name of your project as would be listed on npmjs.com dependencies - a list of packages needed to RUN your project devDependencies - a list of packages need to DEVELOPE or TEST your project scripts - a list of aliased commands your project supports private - set this to true to ensure that your project DOES NOT end up on npmjs.com license - the license under which you are releasing your code UNLICENSED for private packages http://choosealicense.com/ -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 24/46 PACKAGE.JSON FILE (CONTINUED) Interactive guide:
http://browsenpm.org/package.json -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 25/46 HOW TO FIND SELECT /
PACKAGES Search Compare: number of stars / forks number of downloads last contribution date number of open pull requests number of open issues https://www.npmjs.com/ -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 27/46 THE VERY BASICS let http
= require('http'); const PORT = 3000; http.createServer(function (req, res) { res.writeHead( 200, { 'Content-Type': 'text/plain' } ); res.end('Hello World\n'); }).listen(PORT); console.log(`Server running at http://0.0.0.0:${PORT}/`); See on GitHub -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 28/46 USING A 3RD PARTY LIBRARY
let http = require('http'); let status = require('statuses'); const PORT = 3000; http.createServer(function (req, res) { res.writeHead( status('OK'), { 'Content-Type': 'text/plain' } ); res.end('Hello World\n'); }).listen(PORT); console.log(`Server running at http://0.0.0.0:${PORT}/`); -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 29/46 Restarting server on file change
is annoying. Let's setup something to do this for us. Add the following to the object in our file: Now we can simply run: WATCHING FILES npm install --save-dev supervisor scripts package.json "dev": "supervisor --debug index.js" npm run dev -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 31/46 WHAT IS EXPRESS.JS A framework
for Node.js applications Recently added to Node.js Foundation's incubator -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 32/46 WHY USE EXPRESS.JS Aids with:
Parsing of HTTP request bodies Parsing of cookies Managing sessions Organizing routes Determining proper response headers based on data types -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 33/46 UPGRADE OUR APP var express
= require('express'); var app = express(); const PORT = 3000; app.get('/', function (req, res) { res.end('Hello World\n'); }); app.listen(PORT, function () { console.log(`Server running at http://0.0.0.0:${PORT}/`); }); View on GitHub -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 34/46 WHAT DID WE GAIN? Slightly
less code Get routing out of the box Ready for extension via Middlewares -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 35/46 ADD A TEMPLATE ENGINE Default,
but many other engines are available Helps ensure valid HTML Adds includes, extends, variables Much much more... Minifies HTML Jade -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 36/46 Install via: In our app:
In our controller: ADD A TEMPLATE ENGINE (CONT) npm install --save jade app.set('view engine', 'jade'); res.render('index', {msg: 'Welcome to the Practical Node.js!'}) See on GitHub -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 37/46 Require external dependencies with NPM
Configure Express to serve files: Reference the virtual path in your HTML SERVING STATIC FILES npm install --save jquery let virtualPath = '/static'; app.use( virtualPath, [ express.static('node_modules/jquery/dist'), ] ); script(src="static/jquery.min.js") -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 38/46 Created by adding: ROUTING app.VERB(url,
fn1, fn2 ..., fn) url - is a "RegExp" string See fnNs - are request handlers VERB - is one of: all - catch every request (all methods) get - catch GET requests post - catch POST requests put - catch PUT requests del - catch DELETE requests path-to-regexp -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 39/46 REQUEST HANDLERS Take three parameters:
req - Request res - Response next - "just kidding, I don't want to handle this" -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 40/46 Useful methods: REQUEST HANDLERS (CONT)
res - Sets cookie name to value - Transfers file as an “attachment” - Redirects to the URL - Renders a view and sends the rendered HTML - Sends the HTTP response. The body parameter can be a Buffer object, a String, an object, or an Array res.cookie() res.download() res.redirect() res.render() res.send() -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 41/46 WEBSOCKETS WebSockets is an advanced
technology that makes it possible to open an interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event- driven responses without having to poll the server for a reply. -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 42/46 SOCKET.IO Socket.IO enables real-time bidirectional
event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. Use by: Microsoft Office Yammer Zendesk Trello -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 43/46 SOCKET.IO SOCKET COMMANDS // sending
to sender-client only socket.emit('message', "this is a test"); // sending to all clients, include sender io.emit('message', "this is a test"); // sending to all clients except sender socket.broadcast.emit('message', "this is a test"); -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 44/46 SOCKET.IO SOCKET COMMANDS (CONT) //
sending to all clients in 'game' room(channel) except sender socket.broadcast.to('game').emit('message', 'nice game'); // sending to all clients in 'game' room(channel), include sender io.in('game').emit('message', 'cool game'); // sending to sender client, only if they are in 'game' room(channel) socket.to('game').emit('message', 'enjoy the game'); // sending to all clients in namespace 'myNamespace', include sender io.of('myNamespace').emit('message', 'gg'); // sending to individual socketid socket.broadcast.to(socketid).emit('message', 'for your eyes only'); -
2/18/2016 Node.js Fundamentals http://localhost:8000/?print-pdf#/ 45/46 DEPLOYING TO HEROKU 1. Create
an account at 2. Create new app 3. Install the 4. Run the following: https://www.heroku.com Heroku Toolbelt heroku login heroku keys:add ~/.ssh/your_rsa_key.pub heroku git:remote -a practical-node git push heroku master