introduction in node.js (in russian)
TRANSCRIPT
![Page 1: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/1.jpg)
![Page 2: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/2.jpg)
Михаил Давыдов Разработчик JavaScript
Node.js – серверный JavaScript
![Page 3: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/3.jpg)
3
![Page 4: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/4.jpg)
4
История Node.js
• Разработка с 2009 – Ryan Dahl • Поддержка Joyent • Событийный асинхронный I/O • V8 JavaScript от Google • libUV - ядро Node
– событийный ввод-вывод
• Кроссплатформенный (native)
![Page 5: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/5.jpg)
5
Где и почему?
• Node.js = JavaScript + Асинхронность • Приложения реального времени
– Чаты – Серверы игр – Серверы Push-уведомлений
• Нагруженные прокси • Сервисы с большим числом клиентов • Везде, где время I/O больше вычислений
![Page 6: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/6.jpg)
6
Node.js
Node V8 JS
Среда Виртуалка
любой Интерфейс
![Page 7: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/7.jpg)
7
Установка
• http://nodejs.org/download/ • Просто выполняем установочный файл
![Page 8: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/8.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/9.jpg)
9
main.js
console.log('Hello World!');
Запуск файла с node.js
> node main.js Hello World!
![Page 10: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/10.jpg)
Модули в Node.js
CommonJS Module
Глобальные переменные модуля
![Page 11: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/11.jpg)
Любой файл – модуль
![Page 12: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/12.jpg)
Глобальные переменные модуля
• 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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/13.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/14.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/15.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/16.jpg)
16
Запуск файла с node.js
> node main.js /path/to/myOtherModule.js 5.14159
![Page 17: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/17.jpg)
17
Node.js кэширует модули и выполняет их код только 1 раз
![Page 18: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/18.jpg)
18
Другие глобальные переменные
• console – вывод данных в STDOUT – log – dir
• process – информация о текущем процессе – время работы – затраты памяти – Информация о текущей ОС – текущая рабочая папка CWD – PID
• setTimeout, setInterval
http://nodejs.org/api/process.html
![Page 19: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/19.jpg)
NPM
Управление зависимостями
Декларация зависимостей
![Page 20: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/20.jpg)
Задачи npm
• Устанавливает модули из репозитория • Устраняет зависимости • Удаляет не нужные модули • Отправляет ваши модули в репозиторий • …
https://npmjs.org/
![Page 21: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/21.jpg)
21
Зависимости main.js
• main.js – module.js – наш модуль
• module.js – npmModule – не наш модуль – fs – модуль node.js – ../dep.js – наш модуль
![Page 22: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/22.jpg)
22
npmModule может быть не установлен – его нужно задекларировать
![Page 23: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/23.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/24.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/25.jpg)
25
![Page 26: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/26.jpg)
Базовые модули Node
fs
http
http://nodejs.org/api/
![Page 27: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/27.jpg)
27
fs
• Всевозможные функции работы с fs • fs.readFile • fs.writeFile • fs.realpath • …
http://nodejs.org/api/fs.html
![Page 28: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/28.jpg)
28
Каждая функция fs имеет 2 типа: синхронный и асинхронный
![Page 29: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/29.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/30.jpg)
30
Синхронный для CLI Асинхронный для сервера
![Page 31: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/31.jpg)
31
http/https
• Всевозможные функции работы с http • HTTP(S) сервер • Скачивание файлов по сети
– аналоги $.get, $.post
http://nodejs.org/api/http.html
![Page 32: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/32.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/33.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/34.jpg)
34
Все API низкоуровневое
• Объект req – Request – Описывает текущий запрос – Заголовки запроса – Тело запроса – Тип запроса GET POST – URL запроса
• Объект res – Response – Описывает ответ на запрос – Заголовки ответа – Тело ответа – Статус ответа
![Page 35: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/35.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/36.jpg)
36
Как же много писать...
![Page 37: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/37.jpg)
Библиотеки Node.js
express
optimist
colors
…
https://github.com/joyent/node/wiki/modules https://npmjs.org/
![Page 38: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/38.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/39.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/40.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/41.jpg)
41
![Page 42: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/42.jpg)
42
Можно и руками, но сильно дольше…
![Page 43: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/43.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/44.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/45.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/46.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/47.jpg)
47
Можно и руками, но сильно дольше…
![Page 48: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/48.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/49.jpg)
49
Все эти библиотеки можно установить через npm: npm install express!
![Page 50: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/50.jpg)
node+dom
Бонус: node-webkit
![Page 51: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/51.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/52.jpg)
52
node-webkit
Node, DOM V8 JS
Среда Виртуалка
Интерфейс
GUI+*
![Page 53: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/53.jpg)
53
Аналогов много, но node-webkit это первый, кто использует Node.js
![Page 54: Introduction in Node.js (in russian)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/54.jpg)
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)](https://reader034.vdocuments.pub/reader034/viewer/2022051314/557f6b58d8b42aab368b4ab1/html5/thumbnails/55.jpg)
55
Заключение
• Node.js • Npm • Формат модуля
– CommonJS Module/1.0 – exports, module, require – кэширование модуля
• Зависимости проекта – package.json
• Базовые модули • Библиотеки Node.js