Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Node.js Streams

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.
Avatar for Artem Bey Artem Bey
February 07, 2015

Node.js Streams

Доклад для Kharkiv.JS про node.js streams и работу со стримами с помощью highland.js

Avatar for Artem Bey

Artem Bey

February 07, 2015
Tweet

More Decks by Artem Bey

Other Decks in Programming

Transcript

  1. 2 Артём Бей разработчик интерфейсов в YouScan и LeadScanner в

    твиттере @defly_self сервис поиска клиентов в социальных сетях сервис мониторинга чего угодно в тех же сетях
  2. fs.readFile('/etc/passwd',  function  (err,  data)  {      if  (err)  throw

     err;      console.log(data);//'qwerty'   }); fs.writeFile('message.txt',  ‘Oh  my  Node',     function  (err)  {      if  (err)  throw  err;      console.log(‘Fuck  yeah!’);   }); http.request(options,  function(res)  {      res.on('data',  function  (chunk)  {          console.log('BODY:  '  +  chunk);      });   }); var  net  =  require('net');   var  client  =  net.connect({...},          function()  {                  console.log('connected  to  server!');                  client.write('world!\r\n');          });   client.on('data',  function(data)  {          console.log(data.toString());          client.end();   });   client.on('end',  function()  {          console.log('disconnected  from  server');   }); Код разный, но есть что-то общее 8
  3. Highland Библиотека для работы с потоками, в том числе потоками

    высшего порядка • _.() для потоков • От создателя node-async Caolan McMahon • 1172 звёзды на github* *актуально на 6 февраля 2015 14
  4. • Chain API и не только • Генерация стримов из

    многих источников • Методы для преобразование стрима • Стримы высшего порядка • Более приятная обработка ошибок • Примочки из функционального программирования 15
  5. API var  r  =  request.post(...);   _(r)      

       .invoke('toString',  ['utf8'])          .split("\r\n")          .map(JSON.parse)          .filter(maybeSpam)          .pluck("text")          .errors(_.log)          .each(_.log); 16
  6. Источники стримов • массивы • Readable стримы • events •

    callback(err, data) • promise • собственный генератор 17
  7. _('message',  client)   _([1,  2,  3,  4])   _(dbReadableStream)  

    _.wrapCallback(fs.readFile);   _(fetch('/api/foo'))   function  getData(filename)  {          return  _(function(push,  next)  {                  fs.readFile(filename,  function(err,  data)  {                          push(err,  data);                          push(null,  _.nil);                  });          });   }; 18
  8. Что можно делать со стримом? • Split • Фильтровать (find,

    where …) • Сворачивать (reduce, scan, group, uniq etc) • Трансформировать (map, pluck, pick etc) • throttle, debounce, ratelimit 19
  9. Стримы высшего порядка 20 • Копирование, конкатенация, объединение • Map/Filter

    стрима функциями которые возвращают стрим • Выравнивание вложенных стримов
  10. var  nums  =  _(          _([1,  2,

     3]),          _([4,  _([5,  6])  ])   );   nums.flatten();    //  =>  1,  2,  3,  4,  5,  6 _([1,  2]).concat([3,  4])    //  =>  1,  2,  3,  4 _(filenames).flatFilter(checkExists)   //  true  false  true  ...   _(filenames).flatMap(readFile)   //contents  of  files  in  order
  11. Control-flow 22 Обработка источников стримов последовательно и параллельно _(filenames).map(readFile).series()  

      //almost  same  _(filenames).flatMap(readFile)   //  read  from  up  to  10  files  at  once   _(filenames).map(readFile).parallel(10);
  12. Обработка ошибок getDocuments.errors(function  (err,  push)  {        

     if  (err.statusCode  ===  404)  {                  //  not  found,  return  empty  doc                  push(null,  {});          }  else  {                  //  otherwise,  re-­‐throw  the  error                  push(err);          }   }) по человечески:)
  13. Почитать по теме • Stream handbook от substack • Документация

    по Highland • Статью Callback Hell vs. Async vs. Highland • https://github.com/caolan/highland/blob/ master/test/test.js 24