SplitterStream = (options = {}, splitters = [' ','\n'], data = "") ->

  splitter = new require('stream').Transform(options)
  splitter._transform = (chunk,format,done) ->

    chunk = chunk.toString()
    for i in [0..(chunk.length - 1)]
      if chunk[i] in splitters
        if data isnt ''
          @push(data)
          data = ''
      else
        data += chunk[i]
    done()

  splitter._flush = -> if data isnt '' then data else null

  return splitter
[ ]
 

Ошибка:

При работе с transform - стримом выводилась ошибка

$ coffee urlsgenerator.coffee|coffee splitter-case.coffee 
/home/space1000/tst/streams/splitter-case.coffee:8
      this.push(chunk.toString());
           ^
TypeError: undefined is not a function
  at [object Object]._onTimeout (/home/space1000/tst/streams/splitter-case.coffee:5:9)
  at Timer.listOnTimeout (timers.js:110:15)

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write EPIPE
  at exports._errnoException (util.js:746:11)
  at WriteWrap.afterWrite (net.js:766:14)

Причина:

Ошибка не связана с потоками или стримингом. Ошибка была простой ошибкой, которую выкидывает интерпретатор в процессе работы кода. В данном случае она находится в самом верху:

/home/space1000/tst/streams/splitter-case.coffee:8
      this.push(chunk.toString());
           ^
TypeError: undefined is not a function

Однако, ввиду того, что в stdout уже пайпнут вышеупомянутый трасформ-стрим, обычный вывод ошибок, который в ноде идёт не в stderr, а в stdout (интересно, можно ли это изменить?), да и вообще вывод в stdout чего угодно уже считается тяжким преступлением и карается выбрасыванием Error: write EPIPE, что и придаёт обычной с виду ошибке такую мудацкую нечитаемую форму, которая заставляет пенять на какие-то скрытые баги в коде самой ноды или coffeescript или вообще хуй знает чего.

Пример:

urlsgenerator.coffee

rs = (require 'stream').Readable()
rs.drained = false

outputData = 
[
  "http://ya.ru "
  "http://goo"
  "gle.com\n"
  "http://bing.com "
  "http://y"
  "aho"
  "o.com\n"
  "http://rambler.ru"
]

intervalId = setInterval(
  ->
    if rs.drained
      if outputData.length isnt 0
        rs.drained = false
        #console.error(outputData.shift())
        rs.push(outputData.shift())
      else
        rs.push(null)
        clearInterval(intervalId)
  ,250
)

rs._read = ->
  rs.drained = true

rs.pipe(process.stdout)

splitter-case.coffee

ts = new (require 'stream').Transform()
ts._transform = (chunk, encoding, done) ->
  setTimeout(
    ->
      @.push(chunk.toString())
      done()
    ,1000
  )
 
process.stdin.pipe(ts)
ts.pipe(process.stdout)

Вывод:

$ coffee urlsgenerator.coffee|coffee splitter-case.coffee 
/home/space1000/tst/streams/splitter-case.coffee:8
      this.push(chunk.toString());
           ^
TypeError: undefined is not a function
  at [object Object]._onTimeout (/home/space1000/tst/streams/splitter-case.coffee:5:9)
  at Timer.listOnTimeout (timers.js:110:15)

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write EPIPE
  at exports._errnoException (util.js:746:11)
  at WriteWrap.afterWrite (net.js:766:14)

Обновлённый код splitter-case с исправленной (типичной) ошибкой:

ts = new (require 'stream').Transform()
ts._transform = (chunk, encoding, done) ->
  setTimeout(
    =>
      @.push(chunk.toString())
      done()
    ,1000
  )
 
process.stdin.pipe(ts)
ts.pipe(process.stdout)

Результат выполнения той же операции:

$ coffee urlsgenerator.coffee|coffee splitter-case.coffee 
http://ya.ru http://google.com
http://bing.com http://yahoo.com
http://rambler.ru

[ ]
 

Ошибка:
После запуска coffee всегда печатает надпись

Running node v0.11.13

Возможная причина проблемы:

Всё запускается через жопу NVM:

$ cat .bashrc|grep "alias coffee"
alias coffee='nvm run 0.11.13 --harmony /usr/local/bin/coffee'
$ nvm run 0.11.13 /usr/local/bin/coffee 123.coffee
Running node v0.11.13
123

Решение:

Убедиться, что bin/coffee запускается напрямую, а не какими-то окольными путями.

$ /usr/local/bin/coffee 123.coffee
123
[ ]
 

Это

wait1sec = (done) ->
  setTimeout(
    -> 
      console.log("1 sec passed")
      done(null,"1sec")
    ,
    1000
  )
[ ]
 

Ошибка: нодефтп не копирует файлы

@client.get(
  sourcePath,
  false,
  (err,stream) =>
    if err?
      resultCallback err
    else
      @client.put(
        stream,
        destinationPath,
        false,
        (err) ->
          if err?
            resultCallback err
          else
            resultCallback null
      )
)

Причина: line 1014 of connection.js

} else {
  input.pipe(dest);
  input.resume();
}

input.pipe НЕ РАБОТАЕТ ПОТОМУЧТО СТРИМЫ В НОДЕ СЛОМАНЫ НАХУЙ И СОСЕДИ ЗА СТЕНКОЙ ГОЛОВОЙ О СТЕНКУ БЬЮТСЯ, ДЕБИЛЫ, ПОБЕДИТЕЛИ В НОМИНАЦИИ КУРИНЫЕ МОЗГИ 2014
Решение:
Заплатить мне три тысячи долларов, чтобы я пришёл и все исправил.

[ ]
 

Блядь! Какого хера оно его выполняет вместо возврата deferred? Пиздец!

q = require("q")

a = q.Promise (resolve,reject,notify) ->
  setTimeout(
    ->
      bu = Math.random() * 100
      console.log("a", bu)
      resolve(bu)
    ,
    Math.random() * 3000
  )  

b = q.Promise (resolve,reject,notify) ->
  setTimeout(
    ->
      bu = Math.random() * 100
      console.log("b", bu)
      resolve(bu)
    ,
    1000 + Math.random() * 3000
  ) 

Результат вызова:

$ coffee promises_all.coffee 
Running node v0.11.13
a 83.59919420909137
b 5.926010990515351

Ну и что с этим блядь делать? Блядь. Блядь. Блядь.

q = require("q")

q.all([

  q.Promise (resolve,reject,notify) ->
    setTimeout(
      ->
        bu = Math.random() * 100
        console.log("a", bu)
        resolve(bu)
      ,
      Math.random() * 3000
    )
  ,
  q.Promise (resolve,reject,notify) ->
    setTimeout(
      ->
        bu = Math.random() * 100
        console.log("b", bu)
        resolve(bu)
      ,
      1000 + Math.random() * 3000
    ) 
    
])
.then (pizdec) ->
  console.log pizdec

Результат вызова:

$ coffee promises_all.coffee 
Running node v0.11.13
a 28.216111892834306
[ 28.216111892834306 ]
b 73.70093793142587

Сука блядь сука блядь сука блядь сука блядь. Эта сука блядь нихуя не понимает блядь что там блядь массив блядь вместо этого блядь она компилируется блядь в полную блядь хуйню блядь хотя блядь все отступы блядь расставлены блядь правильно блядь сука блядь. Вот блядь правильный вариант, блядь. Скобочек ей не хватает блядь сука блядь что за тупизм блядь.

q = require("q")

q.all([

  (a = q.Promise (resolve,reject,notify) ->
    setTimeout(
      ->
        bu = Math.random() * 100
        console.log("a", bu)
        resolve(bu)
      ,
      Math.random() * 3000
    )
  ),
  (b = q.Promise (resolve,reject,notify) ->
    setTimeout(
      ->
        bu = Math.random() * 100
        console.log("b", bu)
        resolve(bu)
      ,
      Math.random() * 3000
    ) 
  )

])
.then (pizdos) ->
  console.log pizdos

console.log a,b

Результат вывода:

$ coffee promises_all.coffee 
Running node v0.11.13
{ state: 'pending' } { state: 'pending' }
a 87.82047459390014
b 66.98890661355108
[ 87.82047459390014, 66.98890661355108 ]

В общем, грустно всё это.

Ловится:

q = require 'q'
co = require 'co'

tryErr = (genError,done) ->

  q.Promise (resolve,reject,notify) ->

    if genError
      throw "GeneratedError"
    else
      resolve("ok")

  .then (ok) -> 
    q.Promise (resolve,reject,notify) ->

      done()

  .catch (err) ->

    done(err)

  .done()

try
  tryErr(true,-> console.log "success")
catch err
  console.log "catch: " + err

Не ловится:

q = require 'q'
co = require 'co'

tryErr = (genError,done) ->

  q.Promise (resolve,reject,notify) ->

    if genError
      throw "GeneratedError"
    else
      resolve("ok")

  .then (ok) -> q.Promise (resolve,reject,notify) ->

      done()

  .catch (err) ->

    done(err)

  .done()

try
  tryErr(true,-> console.log "success")
catch err
  console.log "catch: " + err

Увы, это требует разбиения на две строки:

  .then (ok) -> q.Promise (resolve,reject,notify) ->
[ ]
 
timestamp = ->
  now = new Date()
  return (
        now.getFullYear() + '-' 
        + ("00" + (now.getMonth()+1)).substr(-2,2) + '-' 
        + ("00" + now.getDate()).substr(-2,2) + ' ' 
        + ("00" + now.getHours()).substr(-2,2) + ':' 
        + ("00" + now.getMinutes()).substr(-2,2) + ':' 
        + ("00" + now.getSeconds()).substr(-2,2) + '.' 
        + ("000" + now.getMilliseconds()).substr(-3,3)
  )

javascript pad strpad

[ ]
 

Co-prompt зависает, если не делать process.stdin.pause() после обработки информации. При первом же yield stdin открывается для чтения и висит, продолжая работать и ожидая событий, до тех пор, пока его явно не закроешь.

[ ]