ele ele - 1 month ago 19
CoffeeScript Question

Calling functions from `coffee` executable

Forgive the noob question, but why is it that I can't call (almost) any standard functions from the

coffee
REPL (or from files written and run within TextMate, for that matter)?

Variable assignment works, functions don't.

Examples:

coffee> string = "string"
'string'
coffee> list = [1,2,3]
[ 1, 2, 3 ]
coffee> num = 42
42
coffee> opposite = true
true
coffee> num = -42 if opposite
-42


but

coffee> alert "Hello, World"
ReferenceError: alert is not defined
at repl:1:5
at REPLServer.replDefaults.eval (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/repl.js:33:28)
at repl.js:239:12
at Interface.<anonymous> (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/repl.js:62:9)
at Interface.EventEmitter.emit (events.js:117:20)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:117:20)


and

coffee> print "Hello"
ReferenceError: print is not defined
at repl:1:5
at REPLServer.replDefaults.eval (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/repl.js:33:28)
at repl.js:239:12
at Interface.<anonymous> (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/repl.js:62:9)
at Interface.EventEmitter.emit (events.js:117:20)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:117:20)


What really gets me is:

coffee> console.log "Help!"
Help!
undefined


I have Node installed via Homebrew and CoffeeScript installed (globally) via
npm
.

Answer

alert is not a feature of javascript. It's part of the API the browser exposes to JavaScript. And coffee at the command line on you computer is just a thin wrapper around node.js that translated coffee script into javascript to be interpreted by node. node.js does not provide an alert function. Nor does it provide a global print function.

Both node, and the browser, do provide a console object globally. So console.log works the same.

Brush up on the node docs to learn what function node exposes. And rememebr that just because it works in a browser does not mean it will work in node.