Running CasperJs scripts from a C# console app

I recently came across the need to write a console application that can take a CasperJs script (or folder) and run it with console output on. I wanted to make this tool in order to integrate it with Visual Studio External tools, so that whenever I am editing a casperJs script, I can hit my keyboard shortcut to verify that all is ok.

Doing this in C# is mostly straightforward:

  • You recieve the CasperJs file or folder to run as an argument to your console app
  • Inspect the environment variables to find:
    • Where Python is installed (by inspecting your path variable)
    • Where CasperJs is installed
  • You start a Process.Process() and provide it with enough details to run the script

 

Challenge: Output

The tricky bit, is to grab the output, and display it in your own app. Here’s my go at it:

private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, 
string casperArguments)
{
    var p                              = new Process();
    p.StartInfo.WorkingDirectory       = workingDir.FullName;
    p.StartInfo.FileName               = pythonPath.FullName;
    p.StartInfo.Arguments              = casperArguments;
    p.StartInfo.UseShellExecute        = false;
    p.StartInfo.CreateNoWindow           = true;
    p.StartInfo.RedirectStandardError  = true;
    p.StartInfo.RedirectStandardInput  = true;
    p.StartInfo.RedirectStandardOutput = true;

    p.ErrorDataReceived += (s, e) => {
        if (!string.IsNullOrEmpty(e.Data))
            Console.WriteLine("e> " + e.Data);
    };

    p.OutputDataReceived += (s, e) => {
        if (!string.IsNullOrEmpty(e.Data))
            Console.WriteLine("->" + e.Data);
    };

    p.Start();
        p.BeginOutputReadLine();
        p.BeginErrorReadLine();
        p.WaitForExit();
    p.Close();
}

 

The tricky bit to figure out was that after you start the processs (p.Start()), you need to call the asynchronous methods BeginOutputReadLine() and BeginErrorReadLine(), otherwise, events will never be posted. Sarching the internet for invoking processes did not include this little gem, hence this post.

Happy coding!

Jeg bare tøyser