Hacking Node – (for fun and profit) – What is node?



Hacking Node – (for fun and profit) – What is node?

0 0


hacking-node

Presentation I gave about node.js

On Github fheemeyer / hacking-node

Hacking Node

(for fun and profit)

What is node?

(Better known as node.js)

What isn't node?

Node is not...

  • ...a web framework
  • ...a web server
  • ...a javascript runtime

Huh?

So what is node?!????

"Node.js is simply a library written for V8 which does evented I/O"

Ahh, V8!

  • Javascript engine
  • Released in September 2008 by Google
  • incomparably fast (about 10x)
  • stand-alone (!)

Right, but...

Javascript has

NO STANDARD LIBRARY

(compared to ruby / python / perl)

to be fair

NODE.js

steps in the game

Node in action

$ echo "console.log('Hello World');" > foo.js
$ node foo.js
Hello World

Does this look familiar?

Compare:

$ echo "puts 'Hello World'" > foo.rb
$ ruby foo.rb
Hello World

With node, javascript feels like a normal script language.

Another example

// Reading files in node.js
var fs = require('fs')
  , argument = process.argv[2];

var contents = fs.readFileSync(argument, 'utf-8');

console.log(contents);
$ echo 'foo' > data.txt
$ node foo.js data.txt
foo

Node adds

  • Libraries (from format strings to evented IO)
  • Module system (a require directive!)
  • A package manager (with dependency managment)

But still...

...why Node?

Pro argument #1

(Just in case you didn't hear it)

It's fast!

V8 Engine

+

Everything runs in 1 process

Java Webserver:

NODE.JS:

Pro argument #2

Javascript

(Is it a client? Is it a server? Who cares!)

Is it worth it?

Contra argument #1

(Just in case you didn't hear it)

Javascript

(Again?)

Example:

/*
 * simple inheritance in node.js
 */

var util = require('util');

// ClassA definition
var ClassA = function() {
  this.a = 'a';
};

// ClassB definition, inherits ClassA
var ClassB = function() {
  ClassA.apply(this, arguments);

  this.b = 'b';
};
util.inherits(ClassA, ClassB);

Ugly?

Might be. But I'm not here to convince anyone.

Lets go on

and see what else node has to offer

NPM

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (foo)
  • Dependency management
  • Acts like bundler
  • package.json
{
  "name": "foo",
  "version": "0.0.1",
  "description": "Lorem ipsum dolor sit amet",
  "main": "index.js",
  "dependencies": {
    "MD5": "~1.2.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Finn-Lennart Heemeyer",
  "license": "ISC"
}
$ npm install
npm WARN package.json finn@0.0.0 No description
npm WARN package.json finn@0.0.0 No repository field.
npm WARN package.json finn@0.0.0 No README data
npm http GET https://registry.npmjs.org/MD5
npm http 304 https://registry.npmjs.org/MD5
npm http GET https://registry.npmjs.org/charenc
npm http GET https://registry.npmjs.org/crypt
npm http 304 https://registry.npmjs.org/crypt
npm http 304 https://registry.npmjs.org/charenc
MD5@1.2.0 node_modules/MD5
├── charenc@0.0.1
└── crypt@0.0.1
$

non-blocking io

& the callback hell

$.ajax({
method: 'get',
url: 'http://www.google.de'
}).then(function() {
  // Asynchronous
  console.log('Second!');
});

console.log('First!');
fs = require('fs');
fs.readFile('/doesnt/exist', 'utf8', function (err,data) {
  // Asynchronous
  if (err) {
    return console.log(err);
  }
  console.log(data);
  console.log('Second!');
});
console.log('First!');

The Callback Hell

function archiveOrders(date, cb) {
  db.connect(function(err, conn) {
    if (err) return cb(err);
    conn.query("select * from orders where date < ?", [date], function(err, orders) {
      if (err) return cb(err);
      helper.each(orders, function(order, next) {
        conn.execute("insert into archivedOrders ...", [order.id, ...], function(err) {
          if (err) return cb(err);
          conn.execute("delete from orders where id=?", [order.id], function(err) {
if (err) return cb(err);
next();
          });
        });
      }, function() {
        console.log("orders have been archived");
        cb();
      });
    });
  });
}
// streamline.js
function archiveOrders(date, _) {
  var conn = db.connect(_);
  conn.query("select * from orders where date < ?", [date], _).forEach_(_, function(_, order) {
    conn.execute("insert into archivedOrders ...", [order.id, ...], _);
    conn.execute("delete from orders where id=?", [order.id], _);
  });
  console.log("orders have been archived");
}

Writing modules

It's easy :)

var myModule = require('lib/my-own-module');

myModule.myModuleFunction('Hi');
var a = myModule.myModuleVariable;
var module = {
  myModuleFunction: function(str) {
    console.log(str);
  },

  myModuleVariable: 1337
};

module.exports = module;

Frameworks

express.js

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);

meteor.js

  • Mongo api usable on server and client
  • Live page updates through websockets
  • Latency compensation
  • Perfect for one-page-apps

Before:

After:

Deployd

THE END

Thanks for listening!