introduction in node.js (in russian)

56

Upload: mikhail-davydov

Post on 16-Jun-2015

585 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Introduction in Node.js (in russian)
Page 2: Introduction in Node.js (in russian)

Михаил Давыдов Разработчик JavaScript

Node.js – серверный JavaScript

Page 3: Introduction in Node.js (in russian)

3

Page 4: Introduction in Node.js (in russian)

4

История Node.js

• Разработка с 2009 – Ryan Dahl • Поддержка Joyent • Событийный асинхронный I/O • V8 JavaScript от Google •  libUV - ядро Node

–  событийный ввод-вывод

• Кроссплатформенный (native)

Page 5: Introduction in Node.js (in russian)

5

Где и почему?

• Node.js = JavaScript + Асинхронность • Приложения реального времени

–  Чаты –  Серверы игр –  Серверы Push-уведомлений

• Нагруженные прокси • Сервисы с большим числом клиентов • Везде, где время I/O больше вычислений

Page 6: Introduction in Node.js (in russian)

6

Node.js

Node  V8  JS  

Среда Виртуалка

любой  Интерфейс

Page 7: Introduction in Node.js (in russian)

7

Установка

• http://nodejs.org/download/ • Просто выполняем установочный файл

Page 8: Introduction in Node.js (in russian)

8

В консоли

> node -v v0.8.8 # npm – Node Package Manager > npm -v 1.1.59 > node -e 'console.log("123")' 123

Запуск

Page 9: Introduction in Node.js (in russian)

9

main.js

console.log('Hello World!');

Запуск файла с node.js

> node main.js Hello World!

Page 10: Introduction in Node.js (in russian)

Модули в Node.js

CommonJS Module

Глобальные переменные модуля

Page 11: Introduction in Node.js (in russian)

Любой файл – модуль

Page 12: Introduction in Node.js (in russian)

Глобальные переменные модуля

• module = {exports:{}, ...};!–  Объект описывающий данный модуль

• exports = {};!–  Объект экспорта данного модуля

• require(moduleName): *!• __filename!• __dirname!

http://nodejs.org/api/modules.html http://nodejs.org/api/globals.html

Page 13: Introduction in Node.js (in russian)

13

require()

• Формат: .js .json .node –  Может быть любой формат (нужно прописать правило) –  Нативные модули на C++

• Имена модулей в require() –  Поведение по умолчанию: –  'имя_модуля' -> npm или базовый node.js –  './путь/до/модуля.js' -> локальный –  './путь/до' -> './путь/до/index.js'

https://github.com/joyent/node/blob/master/lib/module.js

Page 14: Introduction in Node.js (in russian)

14

module.js

var npmModule = require('npmModule'), fs = require('fs'), someMyModule = require('../dep.js'); var myFunction = function (a, b) { return Math.PI * a + b; }; console.log(__filename); exports.myFunction = myFunction; // Или // module.exports = myFunction;

CommonJS Modules/1.0

Page 15: Introduction in Node.js (in russian)

15

main.js

var module = require('./module.js'); typeof module; // object typeof module.myFunction; // function var result = module.myFunction(1, 2); console.log(result); require('./module.js');

CommonJS Modules/1.0

Page 16: Introduction in Node.js (in russian)

16

Запуск файла с node.js

> node main.js /path/to/myOtherModule.js 5.14159

Page 17: Introduction in Node.js (in russian)

17

Node.js кэширует модули и выполняет их код только 1 раз

Page 18: Introduction in Node.js (in russian)

18

Другие глобальные переменные

•  console –  вывод данных в STDOUT –  log –  dir

• process –  информация о текущем процессе –  время работы –  затраты памяти –  Информация о текущей ОС –  текущая рабочая папка CWD –  PID

•  setTimeout, setInterval

http://nodejs.org/api/process.html

Page 19: Introduction in Node.js (in russian)

NPM

Управление зависимостями

Декларация зависимостей

Page 20: Introduction in Node.js (in russian)

Задачи npm

• Устанавливает модули из репозитория • Устраняет зависимости • Удаляет не нужные модули • Отправляет ваши модули в репозиторий • …

https://npmjs.org/

Page 21: Introduction in Node.js (in russian)

21

Зависимости main.js

• main.js –  module.js – наш модуль

• module.js –  npmModule – не наш модуль –  fs – модуль node.js –  ../dep.js – наш модуль

Page 22: Introduction in Node.js (in russian)

22

npmModule может быть не установлен – его нужно задекларировать

Page 23: Introduction in Node.js (in russian)

23

{ "dependencies": { "npmModule": "*", "npmModule": ">=1.0.2", "npmModule": "http://asdf.com/asdf.tar.gz" }, "name": "your-app", "version": "1.0.0", "description": "Hello World!", "author": { "name": "Barney Rubble", "email": "[email protected]" } }

package.json

https://npmjs.org/doc/json.html

Page 24: Introduction in Node.js (in russian)

24

npm install

> wget http://site.ru/your-app.zip > unzip your-app.zip > cd your-app > npm install your-app +-npmModule > node mian.js

Page 25: Introduction in Node.js (in russian)

25

Page 26: Introduction in Node.js (in russian)

Базовые модули Node

fs

http

http://nodejs.org/api/

Page 27: Introduction in Node.js (in russian)

27

fs

• Всевозможные функции работы с fs •  fs.readFile •  fs.writeFile •  fs.realpath • …

http://nodejs.org/api/fs.html

Page 28: Introduction in Node.js (in russian)

28

Каждая функция fs имеет 2 типа: синхронный и асинхронный

Page 29: Introduction in Node.js (in russian)

29

main.js

var fs = require('fs'); fs.readFile('./package.json', 'utf8', file); function file(err, json) { if (err) throw err; console.log(json); } var json = fs.readFileSync('./package.json', 'utf8');

fs

http://nodejs.org/api/fs.html

Page 30: Introduction in Node.js (in russian)

30

Синхронный для CLI Асинхронный для сервера

Page 31: Introduction in Node.js (in russian)

31

http/https

• Всевозможные функции работы с http • HTTP(S) сервер • Скачивание файлов по сети

–  аналоги $.get, $.post

http://nodejs.org/api/http.html

Page 32: Introduction in Node.js (in russian)

32

main.js

var http = require('http'); http.get('http://site/', function (res) { console.log("response: " + res.statusCode); }) .on('error', function (e) { console.log("Got error: " + e.message); });

http – клиент

http://nodejs.org/api/http.html

Page 33: Introduction in Node.js (in russian)

33

var http = require('http'); var server = http.createServer(); server.on('request', function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); server.listen(80, '127.0.0.1');

http – сервер

http://nodejs.org/api/http.html

Page 34: Introduction in Node.js (in russian)

34

Все API низкоуровневое

• Объект req – Request –  Описывает текущий запрос –  Заголовки запроса –  Тело запроса –  Тип запроса GET POST –  URL запроса

• Объект res – Response –  Описывает ответ на запрос –  Заголовки ответа –  Тело ответа –  Статус ответа

Page 35: Introduction in Node.js (in russian)

35

var url = require('url'); // req.url == /?page=pagename&pewpew=ololo function onRequest(req, res) { var data = url.parse(req.url, true), page = data.query.page, userAgent = req.headers['user-agent']; res.setHeader("Set-Cookie", "p=" + page); res.setHeader("Content-Type","text/plain"); res.writeHead(200); res.end(userAgent); }

http – чуть сложнее сервер

http://nodejs.org/api/http.html

Page 36: Introduction in Node.js (in russian)

36

Как же много писать...

Page 37: Introduction in Node.js (in russian)

Библиотеки Node.js

express

optimist

colors

https://github.com/joyent/node/wiki/modules https://npmjs.org/

Page 38: Introduction in Node.js (in russian)

38

// В 5 строк require('express')() .get('/', function (req, res) { res.send('hello world'); }) .listen();

express – http фреймворк

http://expressjs.com/api.html http://expressjs.com/guide.html

Page 39: Introduction in Node.js (in russian)

39

var express = require('express'); var app = express(); var staticDir = __dirname + '/public'; app.get('/', function (req, res){ res.send('hello world'); }); app.use(express.static(staticDir)); app.use(express.logger()); app.listen(3000);

express – http фреймворк

http://expressjs.com/api.html http://expressjs.com/guide.html

Page 40: Introduction in Node.js (in russian)

40

var optimist = require('optimist') .default('port', 80) .default('host', '0.0.0.0'); var cfg = optimist.argv; require('http').createServer(); server.listen(cfg.port, cfg.host);

optimist – CLI парсер

https://github.com/substack/node-optimist

> node main.js --port 81 --host pewpew.com > node main.js

Page 41: Introduction in Node.js (in russian)

41

Page 42: Introduction in Node.js (in russian)

42

Можно и руками, но сильно дольше…

Page 43: Introduction in Node.js (in russian)

43

console.log(process.argv);

CLI парсер руками

> node main.js --port 81 --host pewpew.com > node main.js

[ '/path/to/node', 'main.js', '--port', '80', '--host', 'pewpew.com' ]

Page 44: Introduction in Node.js (in russian)

44

CLI парсер руками

> node main.js --port 81 --host pewpew.com

// argv парсер в 97 байт var argv = (function(a,b,c,d){c={};for(a=a.split(/\s*\B[\/-]+([\w-]+)[\s=]*/),d=1;b=a[d++];c[b]=a[d++]||!0);return c}) (process.argv.join(' ')); console.log(argv); // {port: "81", host: "pewpew.com"}

https://gist.github.com/1497865

Page 45: Introduction in Node.js (in russian)

45

require('colors'); console.log('hello'.green); console.log('i like cake'.underline.red) console.log('OMG Rainbows!'.rainbow);

colors – подсветка консоли

https://github.com/Marak/colors.js

> node main.js hello I like cake OMG Rainbows!

Page 46: Introduction in Node.js (in russian)

46

require('colors'); console.log('hello'.green); console.log('i like cake'.underline.red) console.log('OMG Rainbows!'.rainbow);

colors – подсветка консоли

https://github.com/Marak/colors.js

> node main.js hello I like cake OMG Rainbows!

Page 47: Introduction in Node.js (in russian)

47

Можно и руками, но сильно дольше…

Page 48: Introduction in Node.js (in russian)

48

var red = '\u001b[31m', blue = '\u001b[34m', reset = '\u001b[0m'; console.log( red + 'hello' + reset + ' ' + blue + 'world' + reset);

Цветастая консоль руками

> node main.js hello world

Page 49: Introduction in Node.js (in russian)

49

Все эти библиотеки можно установить через npm: npm install express!

Page 50: Introduction in Node.js (in russian)

node+dom

Бонус: node-webkit

Page 51: Introduction in Node.js (in russian)

51

Цель – десктопные приложения на DOM и Node.js API

https://github.com/zcbenz/nw-sample-apps https://github.com/rogerwang/node-webkit

Page 52: Introduction in Node.js (in russian)

52

node-webkit

Node,  DOM  V8  JS  

Среда Виртуалка

Интерфейс

GUI+*  

Page 53: Introduction in Node.js (in russian)

53

Аналогов много, но node-webkit это первый, кто использует Node.js

Page 54: Introduction in Node.js (in russian)

54

Список файлов в текущей директории

<ol class="b-files-list"></ol> <script src="http://yandex.st/jquery/1.8.2/jquery.min.js"> </script> <script> var fs = require('fs'); fs.readDirSync('.') .forEach(function (file) { $('<li/>') .text(file) .appendTo('.b-files-list'); }); </script>

node-webkit

Page 55: Introduction in Node.js (in russian)

55

Заключение

• Node.js • Npm • Формат модуля

–  CommonJS Module/1.0 –  exports, module, require –  кэширование модуля

• Зависимости проекта –  package.json

• Базовые модули • Библиотеки Node.js

Page 56: Introduction in Node.js (in russian)

56

Михаил Давыдов

Разработчик JavaScript

[email protected] azproduction

Спасибо