Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start a CoffeeScript repl from within a CoffeeScript script?

If I do

repl = require 'repl'

repl.start {useGlobal: true}

It starts a Node repl. How do I start a CoffeeScript repl instead?

Thanks

like image 334
Nick Avatar asked Dec 27 '22 16:12

Nick


2 Answers

Nesh is a project to try and make this a bit easier and extensible:

http://danielgtaylor.github.com/nesh/

It provides a way to embed a REPL with support for multiple languages like CoffeeScript as well as providing an asyncronous plugin architecture, support to execute code in the context of the REPL on startup, etc. For example:

nesh = require 'nesh'

nesh.loadLanguage 'coffee'

nesh.start (err, repl) ->
    nesh.log.error err if err

It also supports a bunch of options with the default plugins and exposes some built-in convenience functions as well:

opts =
    welcome: 'Welcome to my interpreter!'
    prompt: '> '
    evalData: CoffeeScript.compile 'hello = (name="world") -> "Hello, #{world}!"', {bare: true}

nesh.start opts, (err, repl) ->
    nesh.log.error err if err
like image 168
Daniel Avatar answered Dec 29 '22 07:12

Daniel


I think the coffee-script module does not export the REPL functionality to be used programmatically, like the Node repl module does. But CoffeeScript has a repl.coffee file that can be used, even though it's not exported in the main coffee-script module. Taking a hint from command.coffee (which is the file that's executed when you run the coffee command) we can see that the REPL works just by requiring the repl file. So, running this script should start a CoffeeScript REPL:

require 'coffee-script/lib/coffee-script/repl'

This approach, however, is quite hacky. The most important flaw is that it heavily depends on how the coffee-script module works internally and how it's organized. Nothing prevents the repl.coffee file from being moved from coffee-script/lib/coffee-script, or changing the way it works.

A better approach might be calling the coffee command without arguments, just like one would do from the commandline, from Node:

{spawn} = require 'child_process'
spawn 'coffee', [], stdio: 'inherit'

The stdio: 'inherit' option makes the spawned command to read from stdin and write to the stdout of the current process.

like image 28
epidemian Avatar answered Dec 29 '22 06:12

epidemian