Search code examples
c#phantomjsnreco

NReco phantomjs run script async with input and output streams


I'm currently using the NReco phantomjs wrapper and all is well. I call an existing JavaScript file and use a stream to pass in data and an output stream to get the results which I can then turn in to a PNG and insert it into a document.

The code looks a bit like:

using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(serialisedJsonData + "\n")))
using (var outputStream = new MemoryStream())
{
       var phantomJS = new PhantomJS();
       phantomJS.Run("javascriptfile.js", null, inputStream, outputStream);

       ...
}

I would ideally like to call the run method async but I there doesn't seem to be a way to do this with the input and output streams (only with the script filename and args).

Am I missing something or is this not possible?


Solution

  • There are no "RunAsync" method for this set of arguments because of outputStream: in this case wrapper redirects phantomjs's stdout, and output is copied to specified Stream. This is performed by the following code:

        private void ReadStdOutToStream(Process proc, Stream outputStream) {
            var buf = new byte[32 * 1024];
            int read;
            while ((read = proc.StandardOutput.BaseStream.Read(buf, 0, buf.Length))>0) {
                outputStream.Write(buf, 0, read);
            }
        }
    

    and this method is executed inside Run. It is possible to add async version of ReadStdOutToStream that uses Stream.ReadAsync, but currently wrapper has net40 target and this method is not available. Maybe its time to use net45 instead, in this case RunAsync for streams can be added, if it is really needed.