Upload
philipp-fehre
View
283
Download
4
Embed Size (px)
DESCRIPTION
http://github.com/sideshowcoder/javascript-workshop
Citation preview
Something about Node
The basics
What is node.js?
Google’s JavaScript VM V8
POSIX
libuv
Server side JavaScript
Why node.js?
(native) Async I/O
V8 = Speed!
Easy to get started with…
var http = require("http") !var html = "<html>" + "<title>Hello Node</title>" + "<body>Hello Node</body>" + "</html>" !var handler = function(req, res) { res.writeHead(200, { "Content-Type": "text/html" }) res.end(html) } !http.createServer(handler).listen(3000, "127.0.0.1")
It’s all about the ecosystem!
NPM
– James Halliday (http://substack.net/how_I_write_modules)
“If some component is reusable enough to be a module then the maintenance gains are really worth the overhead of making a new project
with separate tests and docs.”
mkdir -p my_thing cd my_thing npm init
package.json
{ "name": "my_thing", "version": "0.0.0", "description": "detect what is my thing", "main": "index.js", "scripts": { "test": "node ./test.js" }, "keywords": [ "my", "thing" ], "author": "sideshowcoder", "license": "BSD-2-Clause" }
index.js
var myThing = function(thing, cb) { if(thing.match(/snowboard*/)) { cb(null, thing + ", is my thing!") } else { cb(thing + ", is not really my thing!") } } !module.exports = myThing
var myThing = require("./") !var handler = function(err, res) { if(err) { console.log(err) return } console.log(res) } !myThing("snowboardng into a beertent", handler) myThing("walking into a beertent", handler) !
Install and use modules
npm install --save minimist
var myThing = require("../my_thing") var argv = require("minimist")(process.argv.slice(2)) !myThing(argv.i, function(err, res) { if(err) return console.error(err) console.log(res) }) !
Build cat in node!
Why node for client side engineering?
Browserify
You can use almost* everything here for webapps
*The browser is not an OS sorry :(
Pitfalls & “Best practices”
Name your functions
myThing(argv.i, function(err, res) { if(err) return console.error(err) console.log(res) }) !
myThing("snowboardng into a beertent", handler) !!
… because!
Beware of the V of evil
doThisFirst(function(err) { if(err) throw err nowDoThis(function() { if(err) throw err andFinallyDoThis() { if(err) throw err done() }) }) })
JavaScript is more OO than you think!
Exceptions are not control flow!
function wait(cb) { setTimeout(cb, 100); } try { wait(function() { throw new Error("Out of time") }) } catch(e) { console.log(e) }
Don’t call the callback more than once!
function going(err, cb) { if(err) cb(err) cb() } !going("wild", function() { console.log("going wild") }) !!