In this recipe, we will learn how to create a custom module for PhantomJS that can be imported into our script using the require
function.
For this recipe, we will only need a text editor. Some knowledge of CommonJS modules is useful but not strictly necessary.
In our text editor, we write the script that will be our module. As PhantomJS adheres to the CommonJS module system, the contents of this file will not pollute the global execution context after being imported; the only aspects of the script that are exposed will be those items attached to the exports
object, and even then it must be assigned to a variable after the require
expression.
For example, we could create our module in the following way:
function parseValue(v) { if (typeof v === 'undefined') { return true; } else { try { return JSON.parse(v); } catch (e) { return v; } } } function parseArguments(args) { return args.reduce(function...