Compiling CoffeeScript from C#

As an experiment, I decided to try this out. I was thinking the other day it would be nice if I could upload a coffeescript file to our CMS at work, and have it generate a corresponding JS file that I can refer to in the views. This is actually pretty straight forward if you have NodeJS installed.

The NodeJS installer also comes with the NPM package manager, which you can use to install CoffeeScript:

npm install -g coffee-script

The most important thing here is to take note of where the binary for coffeescript sits. I used the where command to figure this out:

where coffee

Then all you need is to create a commandline C# project in visual studio, and use the Process class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;


namespace CoffeeConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Process();
            p.StartInfo.UseShellExecute = false;
            // change your path to whatever resulted from the where command usage
            p.StartInfo.FileName = @"C:\Users\aaron\AppData\Roaming\npm\coffee.cmd";
            p.StartInfo.Arguments = "-cp test.coffee";
            p.Start();
            Console.ReadLine();
        }
    }
}

That will output the compiled coffeescript using standard out. You can of course store it into a string and use a StreamWriter to store it into a file, like I want to do. To grab the output, you will need to use a StringBuilder, and a loop as such to grab all the content.

StringBuilder builder = new StringBuilder();

while (!p.HasExited)
{
    builder.Append(p.StandardOutput.ReadToEnd());
}

string output = builder.ToString();
using (StreamWriter javaScriptFile = new StreamWriter("test.js"))
{
    javaScriptFile.Write(output);
}

Be sure to set the following flag as well:

p.StartInfo.RedirectStandardOutput = true;

And that's it. Here's my code in full to checkout, in case you have any issues: http://pastie.org/3525838