8

I am working in CoffeeScript (writing a Cakefile). I would like to compile some other CoffeeScript files, à la

coffee -o lib -c src

I could launch the above command in a child process, but this approach has cross-platform issues and makes error handling difficult. I'd much rather use an API.

I'd be happy to use the exact functions from command.coffee, but I can't work out how.

Addendum: I see require('coffee-script').compile, which compiles a string to another string. That would still leave me to do the grunt work of looping over files and subfolders and writing the output.

1

3 Answers 3

11

The API you're looking for is in coffee-script.coffee. It exports a compile function that does what it says on the tin.

To use command.coffee's run function directly you'd have to first overwrite process.argv with the options you would have passed on the command line.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks I tried over-writing process.argv but I failed to pull it off. Do you have an example?
This works for me: command = require 'coffee-script/lib/coffee-script/command, process.argv.push '-o', 'lib', '-c', 'src', command.run().
Another observation run appears to return before it's finished
@MattHickford Yes it's asynchronous as can be expected in a Node.js package. The source is straightforward—ultimately all compile options call compileScript, and there you can see that it emits "success" and "failure" events. These events pass a task object and on success that object has an output property.
No, but you can add an event listener e.g. CoffeeScript.on( "success", function( task ) { ... } );, which is just as good.
|
7

Just use node's fs API + coffeescript.compile:

fs = require 'fs'
coffee = require 'coffee-script'

fs.readFile 'source.coffee', 'utf8', (err, data) ->
    compiled = coffee.compile data
    fs.writeFile 'source.js', compiled, (err) ->
        console.log "Done."

Also take a look at coffeescript's own Cakefile (uses child processes): https://github.com/jashkenas/coffee-script/blob/master/Cakefile

Comments

0

Thanks Jordan and Linus I wrote:

 command = require('iced-coffee-script/lib/coffee-script/command')
 process.argv[2..]=['-o','lib','-c','src']
 command.run()

Outstanding issues: the run function returns early and there isn't a callback to report error :\

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.