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

隐身守侯 提交于 2020-01-02 05:21:10

问题


If I do

repl = require 'repl'

repl.start {useGlobal: true}

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

Thanks


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/12811744/how-do-i-start-a-coffeescript-repl-from-within-a-coffeescript-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!