Skip to content

Instantly share code, notes, and snippets.

@sukima
Created July 17, 2013 18:54
Show Gist options
  • Save sukima/6023369 to your computer and use it in GitHub Desktop.
Save sukima/6023369 to your computer and use it in GitHub Desktop.

Readline example

readline = require "readline"
rl = readline.createInterface
  input:  process.stdin
  output: process.stdout

Example of named functions

You could use named functions to better read callbacks instead of deeply nested anonymous functions:

onLine

Function for when a line is inputed

onLine = (line) ->
  switch line.trim()
    when "hello"
      console.log "world"

onClose

Function for when the stream closes

onClose = -> # ...

Putting it together

rl
  .on("line", onLine)
  .on("close", onClose)

Example of class encapsulation

Here you could encapsulate the logic in a class:

class ReadlineLoop
  constructor: ->
    @rl = readline.createInterface
      input:  process.stdin
      output: process.stdout
    @rl.on("line", @onLine).on("close", @onClose)
  onLine: => # ...
  onClose: => # ...

And then to run it:

new ReadlineLoop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment