将完整的代码传递给phantomjs

I'm writing a service in Go and I'm using phantomJS to generate an image from a given url. From my Go program, I'm using Exec to start the phantomJS binary. This works fine, but now I'm looking for a way to pass the complete code, together with the call which runs the binary. My code is as follows:

var args = require('system').args;
var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = {
    width: 1920,
    height: 1080
};

page.open("http://www.url2fetch.com", function (status) {
  var base64 = page.renderBase64('PNG');
  console.log(base64);
  phantom.exit();
});

This never changes. Except the url to fetch :). So my concrete question is: is it possible to start phantomJS and pass the code above as a parameter so it can be executed with one call. Reason for this: I don't want to package the phantomjs script together with my Go program.

PhantomJS has an interactive version where you can pass code in through stdin, but there is a bug (versions 1.9.x and 2.0.0) because of which no pages can be opened which makes this effectively unusable.

There is no way to pass a script into PhantomJS to be interpreted. You need to have at least one file. You can either

  1. create a template file which you ship with your executable and call PhantomJS with that file and an additional (URL) parameter or

  2. you generate the file from go into some temporary directory and let PhantomJS use it.

If you have reason to believe that a time-of-write vs. time-of-use vulnerability will be exploited, then you should go with variant 1.

To make the first case complete, you can use system.args in PhantomJS to read the passed commandline options from go such as the URL.

If you are using Linux, you can put this code in the beginning of the PhantomJS script.

#!/usr/bin/env phantomjs

This means, when this file is called, it's like it was called by the terminal.

$ phantomjs script.js args

The interactive version of phantomjs is completely screwed as of writing.

Due to this, if you don't want an extra file in your project, the cleanest way (if you're just distributing a script and not a directory bundle) is to generate a randomly-named js file in the temp directory, run it, and delete it after.