Skip to content
Maciej Brencz edited this page Feb 4, 2015 · 9 revisions

phantomas exposes its API (via CommonJS module) for easy integration with your nodejs code. You can easily perform phantomas runs and gather metrics and asserts results.

Install

npm install phantomas --save

This will install phantomas from npm repository and add a dependency to your project package.json file.

Example

#!/usr/bin/env node
var phantomas = require('phantomas');

console.log(phantomas); // { [Function: phantomas] path: '...', version: '1.0.0' }

phantomas('http://example.com', {"analyze-css": true}, function(err, json, results) {
        console.log([
                'phantomas results',
                err, // null or exit code from phantomas process
                json, // parsed JSON with raw results
                results // results object with metrics values, offenders, asserts data
        ]);
});

Now, run the code:

node example.js

Run in debug mode:

DEBUG=phantomas* node example.js

API

Take a look at the example script

var phantomas = require('phantomas'),
  task;

console.log(phantomas.version); // 1.0.0
console.log(phantomas.metadata.metrics); // metrics metadata - issue #224

task = phantomas(url, options, function(err, json, results) {
  // err: exit code
  // json: parsed JSON with raw results
  // results: results object with metrics values, offenders, asserts data
});

console.log(task.pid); // process ID

// Streams handling
task.stdout.pipe(process.stdout);
task.stderr.pipe(process.stderr);

// Events handling
task.on('progress', function(progress) {
  // reports page loading progress
});

task.on('milestone', function(milestone) {
  // reports page loading milestone - first byte received, onDOMReady, window.onload
});

task.on('log', function(msg) {
  // emitted on every log message sent by phantomas
});

task.on('results', function(results) {
  // results object with metrics values, offenders, asserts data
});

task.on('error', function(exitCode) {
  // reports phantomas exit code (if not zero)
});

Limitations

  • CommonJS module does not handle different reporters as phantomas command line tool does. Metrics are only available as "raw" object or wrapped in results object.
  • CommonJS module does not support multiple runs (--runs switch from CLI tool). You need to create a loop in your code and call phantomas function multiple times.
Clone this wiki locally