Jesus Diaz
Jesus Diaz

Reputation: 165

Automatically close PhantomJs after running script

I want to run PhantomJs scripts from my program, but since the scripts may not be written by me, I need to make sure PhantomJs exits after the execution are either completed or fails for any reason (e.g., invalid syntax, timeout, etc). So far, All I've read says you must always include the instruction phantom.exit() for PhantomJs to exit. Is there any way to automatically close PhantomJs after it executes a given script?

Thanks.

Upvotes: 3

Views: 1045

Answers (1)

Philip Dorrell
Philip Dorrell

Reputation: 1658

Create a file run-javascript.js:

var system = require('system');

try {
  for (var i=1; i<system.args.length; i++) {
    var scriptFileName = system.args[i];
    console.log("Running " + scriptFileName + " ...");
    require(scriptFileName);
  }
}
catch(error) {
  console.log(error);
  console.log(error.stack);
}
finally {
  phantom.exit();
}

Then to run your file myscript.js:

phantomjs run-javascript.js ./myscript.js

You have to include an explicit path for the myscript.js, i.e. ./myscript.js, otherwise phantomjs will look for the script as a module.

There are three execution scenarios that are handled here:

  1. Successful execution, in which case phantom.exit() is called in the finally clause.
  2. Error in the script being run, in which case the require function prints a stacktrace and returns (without throwing any error to the calling code).
  3. Error running the script (e.g. it doesn't exist), in which case the catch clause prints out the stacktrace and phantom.exit() is called in the finally clause.

Upvotes: 2

Related Questions