node.js basics
Qiong Wugfnork webentwicklungsunternehmen
first steps, modules, npm, Events
2
development for the webtraditional desktop applications have a user interface wired up with background logicuser interfaces are based on Windows Forms, Jswing, WPF, Gtk, Qt, etc. and dependant on operating systemon the web user interfaces are standardizedHTML for markupCSS for styleJavaScript for dynamic contentIn the past proprietary technologies existed on the web, e.g. Adobe Flash, ActiveXThey are slowly dying
3
development for the webData is generated on the server, transferred to the client and displayed by the browserServer Side technologies include PHP, JSP, ASP.net, Rails, Djanog, and yes, also node.js
4
node.js – what is it?JavaScript is well known for client-side scripts running inside the browsernode.js is JavaScript running on the server-sideSSJS -> Server-Side JavaScript
Use a language you knowUse the same language for client side and server side
There are a couple of other SSJS systems, e.g. RingoJS, Narwahl, Wakanda, Netscape Enterprise Server (1994)Powered by Google V8 runtimeFast, extendable and scalable
It’s NOT a web framework, and it’s also NOT a language
5
A little theoryThe idea behind node.js
perform asynchronous processing on single thread instead of classical multithread processing, minimize overhead & latency, maximize scalabilityScale horizontally instead of vertically (get more servers instead of more powerful ones) which is consistent with today’s trend towards cloud technologyIdeal for applications that serve a lot of requests but don’t use need lots of computational power per requestNot so ideal for heavy calculations, e.g. massive parallel computingAlso: Less problems with concurrency
6
A little theory
Diagram by Aaron Stannardhttp://www.aaronstannard.com/post/2011/12/14/Intro-to-NodeJS-for-NET-
Developers.aspx
7
A little theoryThere are a couple of implications of this apparently very simple and basic model
Avoid synchronous code at all costs because it blocks the event loopWhich means: callbacks, callbacks, and more callbacks
8
Running node.js Download from nodejs.org Install with Windows Installer apt-get install nodejs on Ubuntu
Try some commands on the interactive shell
node> console.log('Hello World');Hello World
9
Running node.js apart from interactive code shell interpretation, code can be read from
*.js files Let’s create a *.js file and run it with node
E.g. create app.js file Fill it with Code
Run it with
console.log('Hello World');
>node app.jsHello World
Write to node console
run *.js file by executing node *.js
from CLI
10
Webserver exampleThis is the node sample application shown on nodejs.org
and hosts a fully fledged HTTP server, already shows a lot of basic concepts of nodeJS
var http = require('http');
http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n');}).listen(1337, '127.0.0.1');console.log('Server running at http://127.0.0.1:1337/');
Use require keyword to load a module
Call method to create a new HTTP server
write to response stream
define anonymous callback that handles
request event
start accepting connections on port
and hostnameapplication doesn’t exit after last line of codenode.js keeps running until no further events are
possible
11
Webserver exampleThis is the node sample application shown on nodejs.org
and hosts a fully fledged HTTP server, already shows a lot of basic concepts of nodeJS
var http = require('http');
http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n');}).listen(1337, '127.0.0.1');console.log('Server running at http://127.0.0.1:1337/');
Use require keyword to load a module
Call method to create a new HTTP server
write to response stream
define anonymous callback that handles
request event
start accepting connections on port
and hostnameapplication doesn’t exit after last line of codenode.js keeps running until no further events are
possible
12
node.js modules developers know libraries, in node.js modules serve a similar function put different functionalities in different *.js files and allow usage from
other *.js files Helps structuring application
use exports keyword to expose functions to other modules use require keyword to import modules
13
node.js modules create a new file called test.js Expose function with exports keyword
import from main app.js file
exports.helloworld = function () { console.log('Hello World');}
var test = require('./test.js');test.helloworld();
assign helloworld property to exports
object
and assign function to helloworld property, thereby exposing the
function to other modules
require keyword retrieves exports
object defined above
call function stored in helloworld
14
node.js modules It is also possible to directly overwrite the exports object with
module.exports Usually this is done to export the constructor of a JavaScript ‘Class’
and split class definitions to separate filesmodule.exports = function () { this.name = "test object"; this.color = "red"; this.size = "large";}
var test = require('./test.js');var testObject = new test();console.log('name:' + testObject.name);console.log('color:' + testObject.color);console.log('size:' + testObject.size);
assign function to exports object
define JavaScript object constructor
require keyword retrieves exports
object defined above
function test() points to constructor defined
in module.exportscreate new object from constructor
15
node.js modules apart from self written modules, it is also possible to install modules
from a repository with a package manager This package manager is npm Similar command syntax to apt npm install <module name> npm update
huge amount of public packages (74.753 as of 24th May 2014) everyone can contribute
16
structure of a node.js applicationYou need a *.js file that serves as application entry pointRun it directly with node *.js
package.jsondescription of a node.js project in JSON formatSpecifies name, version, description, keywords for your projectdefines dependencies that your project is relying on
17
package.json
{ "name": "TestNodejsApp", "version": "0.0.0", "description": "TestNodejsApp", "private": true, "main": "app.js", "author": { "name": "Qiong Wu", "email": "" }, "dependencies": { "express": "3.4.4", "jade": "*", "stylus": "*" }}
define application entry point
flag project as private, npm refuses to publish
it
define all dependencies that are to be loaded from npm
* means use newest version
18
node.js specific javascript require – handles module management events – implements observer pattern streams – I/O
19
node.js eventsWe‘ve talked about callbacks, asynchronous programming & promisesnode.js is event based and implements the observer patternBasically a subject is defined that keeps track of its dependents called observers and tells them when any relevant state changes
In node.js the EventEmitter class is used to define objects that represent a source of events, usually by inheriting from EventEmitter
20
node.js eventsemitter.on
emitter.once
server.on('connection', function (stream) { console.log('someone connected!');});
server.once('connection', function (stream) { console.log('Ah, we have our first user!');});
21
node.js events
function Test(colour) { this.colour = colour; events.EventEmitter.call(this); this.sendEvent = function() { this.emit('EventSent'); }} Test.prototype.__proto__ = events.EventEmitter.prototype; var testObject = new Test('white'); testObject.on('EventSent', function() { console.log('Event received'); });testObject.sendEvent();
Call EventEmitter Constructor on object
Evoke all bound eventshandlers
Inherit Prototype fro EventEmitter
22
streamsPerform I/O with node.jsfor web applications response object is most common stream objectwritable
writable.writeThis method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.writeable.endCall this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event.
23
streams
// write 'hello, ' and then end with 'world!'http.createServer(function (req, res) { res.write('hello, '); res.end('world!'); // writing more now is not allowed!});
24
Tools of the tradeIDEs for node.jsonline IDE like cloud9Eclipse with node.js pluginsVisual Studio node.js ToolkitJetbrains Webstormlots of other IDEs: webmatrix, coderunner, Expresso, Atom, etc.
We really like Jetbrains Webstorm & Visual Studio with node.js