– an introduction



– an introduction

0 0


nodejs-part1-presentation


On Github Neoklosch / nodejs-part1-presentation

an introduction

Overview

  • based on Chrome's JavaScript runtime V8
  • V8 is written in C++
  • Just-In-Time Compilation
  • good performance

Overview

  • Single-Threading, but Multi-Threading is activatable
  • for non-blocking I/O using events
  • callback pattern
  • you can create webserver or terminal programms
  • platform independent

Example - Simple Webserver

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/');

Moduls

  • npm (total packages: > 64k)
  • npm folder in project folder or global
  • easy to install, easy to remove, easy to manage
  • moduls are written in JavaScript or C++

Node.js is good for

  • small up to medium websites
  • REST server
  • push server
  • terminal programms

Node.js is not good for

  • large and complex websites
  • content management systems
  • high secure systems

Tools written in Node.js

Moduls you must know

Workshop

First connection

var net = require('net');
var client = net.connect({host: '192.168.178.189', port: 8124}, function() {
    console.log('client connected');
});

Check if client disconnected

client.on('end', function() {
    console.log('client disconnected');
});

Receive first data

client.on('data', function(data) {
    console.log(data.toString());
    client.end();
});

run script first time

node app.js

Wrapp in function

function sendDataToServer(output) {
    // Your stuff here
}

Modify connection to send data

var client = net.connect({host: '192.168.178.189', port: 8124}, function() {
    console.log('client connected');
    client.write(JSON.stringify(output));
});

Write first package.json

{
    "name": "nodejs-part1-client",
    "version": "0.0.1",
    "dependencies": {
        "prompt": "0.2.12"
    },
    "engines": {
       "node": ">= 0.8.0"
    }
}

install prompt

npm install

include prompt

var net = require('net'),
    prompt = require('prompt');

prompt.start();

write schema for prompt

var schema = {
    properties: {
        text: {
            required: true
        },
        color: {
            pattern: /^#{1,1}[a-fA-F0-9]{6,6}$/,
            message: 'Hex value must begin with a # and must be only letters from a to z or numbers from 0 to 9 with a length of 6',
            required: false
        }
    }
};

wrap it prompt

prompt.get(schema, function(err, result) {
    if (err) {
        throw err;
    }

    var output = {};

    output['text'] = result.text;
    if ('color' in result && result.color !== '') {
        output['color'] = result.color;
    }

    sendDataToServer(output);
});

run again

node app.js

for all who have slept the last hour

git clone https://github.com/Neoklosch/nodejs-part1-client

further reading