Loading

Starting NodeJS

Igor Suvorov

This is a live streamed presentation. You will automatically follow the presenter and see the slide they're currently on.

Starting NodeJS

План

 

  • Архитектура JavaScript
  • Алгоритмы и паттерны
  • NPM и популярные пакеты
  • Практические задачи

 

Азы JavaScript

 

Типы

 

typeof 123 // "number"

typeof true // "boolean"

typeof "foo" // "string"

typeof {id:12, name: "John"} // "object"

typeof [1, 4, 9] // "object"

typeof null // "object"  (1)

typeof undefined // "undefined"

typeof function(){ return 1+1; } // "function"  (2)

P.S.  Lodash; _.isArray(ar)

RegExp

 

var re = /ab*c/ig;
var re = new RegExp('ab*c', 'ig');

// ac
// Abc
// aBBBBBBBc

var str = "HelloaBBBBBBBcWorld Hacker";
str.replace(re, ' JS ');
// Hello JS World H JS ker

Date

 

var date = new Date();
// Wed Feb 17 2016 16:01:50 GMT+0400 (SAMT)

var str = "Wed Feb 17 2016 16:01:50 GMT+0400 (SAMT)"
var date = new Date(str);

var str = date.toISOString();
// 2016-02-17T12:01:50.000Z

var timestamp = date.getTime();  1455710510000
timestamp = 1*date;
timestamp = +date;

P.S.  MomentJS

JSON

 

var user = {
    firstName: "John",
    lastName: "Connor",
    age: 8 * 2
};

var json = JSON.stringify(user);
// {firstName:"John",lastName: "Connor",age:16}


/**
 * Как-то отправляем в браузер, и как-то принимаем
 */

var user = JSON.parse(json);
if(user.age < 18){
    alert("Вход запрещен");
}

Архитектура V8

Event Loop

Почему это выгодно

Почему это выгодно

Асинхронность

Сравним

// Синхронно

var rounded = Math.round(1.5);
// do something else


/////////


// Асинхронно
var data = null;
getData({userId:123}, function(raw){
    data = Math.round(raw);
    // do something else
})

// чтото паралельное

Как принято?

function getData(server, userId, /*...*/ next){
    // do something
}

//////////

getData("https://vk.com", 1, 
    function(err, user, html /*...*/){
    

})

Что делать нельзя?

while(new Date().getTime() < now + 1000) {  
    // ничего не делаем
}

console.log("Прошла одна секунда, друг")

/// Запрос к базе
/// Запрос на диск
/// Запрос в гугл
  • Всегда 1 процесс 1 поток (v8)
  • Не существует функции sleep()


Как быть?

setTimeout(function(){

    console.log("Прошла одна секунда, друг")
    
    /// Запрос к базе
    /// Запрос на диск
    /// Запрос в гугл
}, 1000);

problems

setTimeout(function(){

    console.log("Прошла одна секунда, друг")
    
    requestToDB({userId:12}, function(err, user){
        if(err){
            return showError(err);
        }else{         
            getFile("suvorov.json", function(err, userJson){
                if(err){
                    return showError(err);
                }
            
                getGoogle("Суворов Игорь", function(err, data){
                    if(err){
                        return showError(err);
                    }
    
                    showSuccess(user,userJson,data)
            
                })
            })
        }
    })
}, 1000);

Сallback hell

 

Pyramid of Doom

Например, Promises

Классы, Наследование

  • Функциональное наследование
  • Наследование через _.extend
  • Прототипное наследование
  • ES6 Классы

Прототипное наследование

NPM

Packages.json

> npm init
> npm install
> npm install lodash express svg2png
> npm start
> npm run test

{
  "name": "svg",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "run": "node index.js",
    "start": "node index.js",
    "prod": "npm install && node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "isuvorov",
  "license": "ISC",
  "dependencies": {
    "lodash": "^3.10.1",
    "express": "^4.13.4",
    "svg2png": "^3.0.0"
  }
}

Фреймворки

Алгоритмы

Полезные пакеты

PUSH-notofication

  • node-gcm - A NodeJS wrapper library port to send data to Android devices via Google Cloud Messaging
  • node-apn - Apple Push Notification module for Node.js

Что почитать?

А также, очень много много ссылок на nodejs библиотеки и туториалы

Ложка дегтя

Спасибо за внимание

Вопросы?

  • isuvorov.ru
  • vk.com/igor.suvorov
  • github.com/isuvorov

Игорь Суворов

ставьте лайк, подписывайтесь на канал

Made with Slides.com