jashkenas--coffeescript/lib/repl.js

42 lines
1.3 KiB
JavaScript
Raw Normal View History

2010-01-30 03:51:51 +00:00
(function(){
var CoffeeScript, helpers, prompt, run, stdin;
// A very simple Read-Eval-Print-Loop. Compiles one line at a time to JavaScript
// and evaluates it. Good for simple tests, or poking around the **Node.js** API.
// Using it looks like this:
// coffee> puts "$num bottles of beer" for num in [99..1]
// Require the **coffee-script** module to get access to the compiler.
CoffeeScript = require('./coffee-script');
helpers = require('./helpers').helpers;
// Our prompt.
2010-01-30 03:51:51 +00:00
prompt = 'coffee> ';
// Quick alias for quitting the REPL.
helpers.extend(global, {
quit: function quit() {
return process.exit(0);
}
});
// The main REPL function. **run** is called every time a line of code is entered.
// Attempt to evaluate the command. If there's an exception, print it out instead
// of exiting.
run = function run(buffer) {
2010-02-18 04:51:43 +00:00
var val;
2010-01-30 03:51:51 +00:00
try {
val = CoffeeScript.run(buffer.toString(), {
no_wrap: true,
globals: true,
source: 'repl'
});
2010-01-30 03:51:51 +00:00
if (val !== undefined) {
p(val);
}
} catch (err) {
puts(err.stack || err.toString());
}
return print(prompt);
};
// Start up the REPL by opening **stdin** and listening for input.
stdin = process.openStdin();
stdin.addListener('data', run);
2010-01-30 03:51:51 +00:00
print(prompt);
})();