working on it ...

Filters

Explore Public Snippets

Sort by

Found 170 snippets matching: casperjs

    public by Gabrielyan  2061  0  6  1

    Quick link checker with CasperJS

    casper = require("casper").create()
    errors = []
    
    errorHandler = (url, status, msg)->
        errors.push {url: url, status: status, msg: msg}; 
    
    
    if casper.cli.has(0)
        url = casper.cli.get(0)
    else 
        casper.echo "Missing url argument", "ERROR"
        casper.exit()
    
    #----------------------------------------------------
    
    casper.start url, (res)->  
        if not res.status or res.status isnt 200 
            errorHandler(url, res.status, res.statusText or 'Something Wrong')
            
        links = @getElementsAttribute('a', 'href')
        
        links = links.filter (link)-> # if need...
            link isnt '#'
            
        @each links, (self, link) ->
            self.thenOpen link, (res) ->
                if res.status and res.status is 200
                    @echo "#{link} - #{res.status} #{res.statusText}", 'INFO'
                else
                    errors.push {url: link, status: res.status, msg: res.statusText}
        
    .run ->
        if errors.length > 0
            @echo "Errors: #{errors.length}"
            for error in errors 
                @echo "url: #{error.url},  status: #{error.status},  msg: #{error.msg}", 'ERROR'
        else 
            @echo "All Done!", "INFO"
                
        @exit()

    external by gorgogol  103  0  2  0

    Boilerplate casperjs scraper. #casperjs

    Boilerplate casperjs scraper. #casperjs: boilerplateCasperScraper.js
    var casper = require('casper').create();
    
    casper.start('http://en.wikipedia.org/', function(){
    
    // ...
    
    });
    
    casper.then(function(){
    
    // ...
    
    });
    
    casper.run();
    
    

    external by ruudud  14377  112  5  0

    Setting cookies before page load in a CasperJS test.

    Setting cookies before page load in a CasperJS test.: casper.cookies.spec.js
    casper.test.setUp(function () {
      casper.echo('Cookies enabled?: ' + phantom.cookiesEnabled);
      phantom.addCookie({
          domain: '.localhost',
          name: 'sessionId',
          value: '12345abcd6789efg'
      });
      casper.start("http://localhost:8000/test_index.html#pageRequiringLogin", function () {
        casper.echo('Start callback has cookie: ' + JSON.stringify(phantom.cookies));
      });
    });
    casper.test.begin("Should do usefull stuff", function (test) {
      // …
    });
    
    

    external by gorgogol  34  0  1  0

    A skeleton for a casperjs test. #casperjs

    A skeleton for a casperjs test. #casperjs: boilerplateCasperTest.js
    casper.test.begin('Test', numTests, function(test){
    
         casper.start('http://en.wikipedia.org/', function(){
              //...
         });
    
         casper.then(function(){
              //...
         });
    
         casper.run(function(){ test.done();});
    });
    
    

    external by codepreneur  1028  1  4  0

    Cheatsheet: CasperJS, PhantomJS & Spooky. More: http://journal.gentlenode.com/casperjs-2-cheatsheet-phantomjs-and-spooky/

    Cheatsheet: CasperJS, PhantomJS & Spooky. More: http://journal.gentlenode.com/casperjs-2-cheatsheet-phantomjs-and-spooky/: casperjs.cheatsheet.js
    // PhantomJS Cheatsheet
    
    $ brew update && brew install phantomjs  // install PhantomJS with brew
    
    phantom.exit();
    
    var page = require('webpage').create();
    
    page.open('http://example.com', function() {});
    page.evaluate(function() { return document.title; });
    page.render('example.png');
    
    page.onConsoleMessage = function(msg) { console.log(msg); };
    page.onResourceRequested = function(request) { console.log('Request ' + JSON.stringify(request, undefined, 4)); };
    page.onResourceReceived = function(response) {  console.log('Receive ' + JSON.stringify(response, undefined, 4)); };
    page.onError = function(msg, trace) { console.log(msg); ... }
    
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {} );
    
    
    // CasperJS Module Cheatsheet
    
    $ brew install casperjs --devel  // install CasperJS with brew
    
    var casper = require('casper').create({
      clientScripts: [
        'includes/jquery.js',
        'includes/underscore.js'
      ],
      exitOnError: true,
      httpStatusHandlers: { },
      logLevel: "error",
      onAlert: null,
      onDie: null,
      onError: null,
      onLoadError: null,
      onPageInitialized: null,
      onResourceReceived: null,
      onResourceRequested: null,
      onStepComplete: null,
      onStepTimeout: null,
      onTimeout: null,
      onWaitTimeout: null,
      page: null,
      pageSettings: {
        javascriptEnabled: true,
        loadImages: false,
        loadPlugins: false,
        localToRemoteUrlAccessEnabled: false,
        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)",
        userName: null,
        password: null,
        XSSAuditingEnabled: false,
      },
      remoteScripts: [ ],
      safeLogs: [ ],
      stepTimeout: null,
      timeout: null,
      verbose: true,
      viewportSize: null,
      retryTimeout: 100,
      waitTimeout: 5000,
    });
    
    casper.options.waitTimeout = 1000;  // alter an option at runtime
    
    casper.cli.args
    casper.cli.options
    casper.cli.has(); casper.cli.get(); casper.cli.drop();
    
    casper.back(), 
    casper.exit([int status]);
    caper.forward();
    casper.run(fn onComplete[, int time]);
    casper.start(String url[, Function then]);
    casper.then(Function then);
    casper.thenBypass(Number nb);
    casper.thenBypassIf(Mixed condition, Number nb);
    casper.thenBypassUnless(Mixed condition, Number nb);
    casper.thenClick(String selector[, Function then]);
    casper.thenEvaluate(Function fn[, arg1[, arg2[, ...]]]);
    casper.thenOpen(String location[, mixed options]);
    casper.thenOpenAndEvaluate(String location[, Function then[, arg1[, arg2[, ...]]]);
    
    casper.base64encode(String url[, String method, Object data]);
    casper.bypass(Numbr nb);
    
    casper.click(String selector);
    casper.clickLabel(String label[, String tag]);
    
    casper.capture(String targetFilepath, Object clipRect);
    casper.captureBase64(String format[, Mixed area]);
    casper.captureSelector(String targetFile, String selector);
    
    casper.clear();  // clears the current page execution environment context
    casper.debugHTML([String selector, Boolean outer]);
    casper.debugPage();
    casper.die(String message[, int status]);
    
    casper.download(String url, String target[, String method, Object data]);
    
    casper.each(Array array, Function fn);
    casper.eachThen(String message[, String style]);
    
    casper.echo(String message[, String style]);
    casper.evaluate(Function fn[, arg1[, arg2[, …]]]);
    casper.evaluateOrDie(Function fn[, String message]);
    casper.exists(String selector);
    casper.fetchText(String selector);
    
    casper.log(String message[, String level, String space]);
    
    casper.fill(String selector, Object values[, Boolean submit]);  // fields are referenced by name attribute
    casper.fillSelectors(String selector, Object values[, Boolean submit]);  // fields are referenced by css3 selectors
    casper.fillXPath(String selector, Object values[, Boolean submit]);  // fields are referenced by XPath selectors
    
    casper.getCurrentUrl();
    casper.getElement(s)Attribute(String selector, String attribute);
    casper.getElement(s)Bounds(String selector);
    casper.getElement(s)Info(String selector);
    casper.getFormValues(String selector);
    casper.getGlobal(String name);
    casper.getHTML([String selector, Boolean outer]);
    casper.getPageContent();
    casper.getTitle();
    
    casper.mouseEvent(String type, String selector);  // mouseup, mousedown, click, mousemove, mouseover, mouseout
    
    casper.open(String location, Object Settings);  // settings: method, data, headers
    casper.reload([Function then];
    casper.repeat(int times, Function then);
    casper.resourceExists(Mixed test);
    casper.sendKeys(Selector selector, String keys[, Object options]);  // options: keepFocus, modifiers
    casper.setHttpAuth(String username, String password);
    casper.status(Boolean asString);
    
    casper.toString();
    casper.userAgent(String agent);
    casper.viewport(Number width, Number height[, Function then]);
    casper.visible(String selector);
    
    casper.unwait();
    casper.wait(Number timeout[, Function then]);
    casper.waitFor(Function testFx[, Function then, Function onTimeout, Number timeout]);
    casper.waitForPopup(String|RegExp urlPattern[, Function then, Function onTimeout, Number timeout]);
    casper.waitForResource(Function testFx[, Function then, Function onTimeout, Number timeout]);
    casper.waitForUrl(String|RegExp url[, Function then, Function onTimeout, Number timeout]);
    casper.waitForSelector(String selector[, Function then, Function onTimeout, Number timeout]);
    casper.waitWhileSelector(String selector[, Function then, Function onTimeout, Number timeout]);
    casper.waitForSelectorTextChange(String selectors[, Function then, Function onTimeout, Number timeout]);
    casper.waitForText(String text[, Function then, Function onTimeout, Number timeout]);
    casper.waitUntilVisible(String selector[, Function then, Function onTimeout, Number timeout]);
    casper.waitWhileVisible(String selector[, Function then, Function onTimeout, Number timeout]);
    casper.warn(String message);
    casper.withFrame(String|Number frameInfo, Function then);
    casper.withPopup(Mixed popupInfo, Function then);
    casper.zoom(Number factor);
    
    casper.on(String event, Function then);
    casper.emit(String event);
    
    // Events referenced: back, capture.saved, click, complete.error, die, downloaded.file, error, exit, fill, forward,
    // http.auth, http.status.[code], load.started, load.failed, load.finished, log, mouse.click, mouse.down, mouse.move,
    // mouse.up, navigation.requested, open, page.created, page.error, page.initialized, page.resource.received, page.resource.requested,
    // popup.created, popup.loaded, popup.close, popup.created, remote.alert, remote.callback, remote.message, resource.received, resource.requested,
    // run.complete, run.start, starting, started, step.added, step.complete, step.created, step.error, step.start, step.timeout, timeout, url.changed,
    // viewport.changed, wait.done, wait.start, waitFor.timeout
    
    casper.setFilter(String event, Function then);
    
    // Filters referenced: capture.target_filename, echo.message, log.message, open.location, page.confirm, page.prompt
    
    
    // CasperJS Utils Module Cheatsheet
    
    var utils = require('utils');
    
    utils.betterTypeOf(input);
    utils.dump(value);
    utils.fileExt(file);
    utils.fillBlanks(text, pad);
    utils.format(f);
    utils.getPropertyPath(Object obj, String path);
    utils.inherits(ctor, superCtor);
    
    utils.isArray(value);
    utils.isCasperObject(value);
    utils.isClipRect(value);
    utils.isFalsy(subject);
    utils.isFunction(value);
    utils.isJsFile(file);
    utils.isNull(value);
    utils.isNumber(value);
    utils.isObject(value);
    utils.isString(value);
    utils.isTruthy(subject);
    utils.isType(what, type);
    utils.isUndefined(value);
    utils.isWebPage(what);
    utils.mergeObjects(origin, add);
    utils.node(name, attributes);
    utils.serialize(value);
    utils.unique(array);
    
    
    // Spooky Cheatsheet (Spooky is used to control CasperJS from the Node environment)
    
    var spooky = new Spooky({
      child: {
        'transport': "http",
        'proxy': '192.128.101.42:9001',  // when you want to switch a proxy (kind of thing I like with Spooky)
        'proxy-auth': 'username:password'
      },
      casper: {
        logLevel: "debug",  // can also be set to "info", "warning" or "error"
        verbose: false
        pageSettings: {
          userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36'
        }
      }
    }, function() {
      // The magic begins here.
    })
    
    // Passing values between spooky environment (NodeJS) to CasperJS.
    spooky.then([{ x: x }, function () { console.log('x:', x); }]); // function tuples
    spooky.thenEvaluate(function (x) { console.log('x:', x); }, { x: x }); // argument hashes
    
    
    
    

    external by tsjk  531  0  3  0

    Rebooting a NETGEAR Gateway CG3700EMR-1CMNDS using CasperJS. Usage: casperjs reboot--CG3700EMR-1CMNDS.js <routerIP> <adminLogin> <admiPassword>

    Rebooting a NETGEAR Gateway CG3700EMR-1CMNDS using CasperJS. Usage: casperjs reboot--CG3700EMR-1CMNDS.js : reboot--CG3700EMR-1CMNDS.js
    var casper = require('casper').create();
    var utils = require('utils');
    
    casper.start();
    
    casper.setHttpAuth(casper.cli.get(1), casper.cli.get(2));
    
    casper.thenOpen('http://' + casper.cli.get(0) + '/RouterStatus.htm', function() {
    	this.echo(this.getTitle() + ': Logged in.');
    });
    
    casper.wait(5000, function() {
    	this.echo(this.getTitle() + ': Issuing reboot.');
    	this.evaluate(function () {
    		document.forms[0].buttonSelect.value="2";
    		document.forms[0].submit(document.forms[0]);
    	});
    });
    
    casper.run();
    
    

    external by Diego Allen  332  1  3  0

    Ejemplo para extraer datos básicos del contribuyente de marangatu usando casperjs. Uso: casperjs datosBasicosContribuyente.js --ruc=ruc --password=password

    Ejemplo para extraer datos básicos del contribuyente de marangatu usando casperjs. Uso: casperjs datosBasicosContribuyente.js --ruc=ruc --password=password: datosBasicosContribuyente.js
    var casper = require('casper').create({
        clientScripts: ['jquery.js'],
    });
    
    var data = {};
    var ruc = casper.cli.get('ruc');
    var password = casper.cli.get('password');
    
    
    casper.start('https://marangatu.set.gov.py/eset/').thenEvaluate(function login(ruc, password) {
        $('#usuarioId').val(ruc);
        $('input[name=j_password]').val(password);
        $('form[name=logonForm]').submit();
    }, ruc, password);
    
    casper.then(function goToProfile() {
        this.echo("Abriendo popup de registro unico");
        this.clickLabel('CONSULTAR REGISTRO UNICO', 'td');
    });
    
    casper.waitForPopup(/.*datosBasicosContribuyente.*$/, function() {
        this.echo("Popup listo");
    });
    
    casper.withPopup(/.*datosBasicosContribuyente.*$/, function getProfileData() {
        data.ruc = this.getElementAttribute('#ruc', 'value');
        data.dv = this.getElementAttribute('#dv', 'value');
        data.contributorType = this.getElementAttribute('#tipoContribuyente', 'value');
        data.contributorCategory = this.getElementAttribute('#categoriaContribuyente', 'value');
        this.echo('Datos basicos');
        this.echo(JSON.stringify(data));
    });
    
    casper.thenOpen('https://marangatu.set.gov.py/eset/logout.do', function logout() {
        this.echo('Cerrando sesion');
    });
    
    casper.run();
    
    

    external by Andreas Nurbo  269  0  3  0

    If you have issues with Rect and testing with CasperJS use the code below to enable bind in PhantomJS. Source is: http://blog.mraiur.com/2015/07/casperjs-reactjs/

    If you have issues with Rect and testing with CasperJS use the code below to enable bind in PhantomJS. Source is: http://blog.mraiur.com/2015/07/casperjs-reactjs/: casperjs-react.js
    casper.on('page.initialized', function() {
            casper.evaluate(function() {
                var isFunction = function(o) {
                    return typeof o == 'function';
                };
     
                var bind,
                    slice = [].slice,
                    proto = Function.prototype,
                    featureMap;
     
                featureMap = {
                    'function-bind': 'bind'
                };
     
                function has(feature) {
                    var prop = featureMap[feature];
                    return isFunction(proto[prop]);
                }
     
                // check for missing features
                if (!has('function-bind')) {
                    // adapted from Mozilla Developer Network example at
                    // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
                    bind = function bind(obj) {
                        var args = slice.call(arguments, 1),
                            self = this,
                            nop = function() {
                            },
                            bound = function() {
                                return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
                            };
                        nop.prototype = this.prototype || {}; // Firefox cries sometimes if prototype is undefined
                        bound.prototype = new nop();
                        return bound;
                    };
                    proto.bind = bind;
                }
            });
        });
    
    

    external by gorgogol  6  0  1  0

    Returns number of google results for search of given term. (example: casperjs --key=java searchGoogle.js) #casperjs

    Returns number of google results for search of given term. (example: casperjs --key=java searchGoogle.js) #casperjs: googleResultsCount.js
    var casper = require('casper').create({
        verbose: true,
        logLevel: "debug"
    });
    
    var key = casper.cli.options['key'];
    var url = 'http://www.google.com';
    
    casper.start(url);
    
    casper.then(function(){
    
       this.fill("form", {'q': key}, true );
    
    });
    
    casper.then(function(){
    
       this.echo(this.fetchText("#resultStats").match(/\d.*\d/));
    
    });
    
    casper.run();
    
    

    external by Radim Daniel Pánek  10553  81  4  0

    CasperJS bootstrap / Phantomjs 2.0 fix

    CasperJS bootstrap / Phantomjs 2.0 fix: bootstrap.js
    /*!
     * Casper is a navigation utility for PhantomJS.
     *
     * Documentation: http://casperjs.org/
     * Repository:    http://github.com/n1k0/casperjs
     *
     * Copyright (c) 2011-2012 Nicolas Perriault
     *
     * Part of source code is Copyright Joyent, Inc. and other Node contributors.
     *
     * Permission is hereby granted, free of charge, to any person obtaining a
     * copy of this software and associated documentation files (the "Software"),
     * to deal in the Software without restriction, including without limitation
     * the rights to use, copy, modify, merge, publish, distribute, sublicense,
     * and/or sell copies of the Software, and to permit persons to whom the
     * Software is furnished to do so, subject to the following conditions:
     *
     * The above copyright notice and this permission notice shall be included
     * in all copies or substantial portions of the Software.
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
     * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
     * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
     * DEALINGS IN THE SOFTWARE.
     *
     */
    
    /*global process, console, phantom, slimer, require:true*/
    /*jshint maxstatements:34, maxcomplexity:10*/
    
    // node check
    if ('process' in this && process.title === "node") {
        console.error('CasperJS cannot be executed within a nodejs environment');
        process.exit(1);
    }
    
    // phantom check
    if (!('phantom' in this)) {
        console.error('CasperJS needs to be executed in a PhantomJS environment http://phantomjs.org/');
    }
    
    // Common polyfills
    if (typeof Function.prototype.bind !== "function") {
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
        Function.prototype.bind = function (oThis) {
            "use strict";
            /* jshint -W055 */
            if (typeof this !== "function") {
                // closest thing possible to the ECMAScript 5 internal IsCallable function
                throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
            }
            var aArgs = Array.prototype.slice.call(arguments, 1),
                fToBind = this,
                fNOP = function() {},
                fBound = function() {
                  return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
                                       aArgs.concat(Array.prototype.slice.call(arguments)));
                };
            fNOP.prototype = this.prototype;
            fBound.prototype = new fNOP();
            return fBound;
        };
    }
    
    // Custom base error
    var CasperError = function CasperError(msg) {
        "use strict"
        Error.call(this);
        this.message = msg;
        this.name = 'CasperError';
    };
    CasperError.prototype = Object.getPrototypeOf(new Error());
    
    // casperjs env initialization
    (function(global, phantom){
        /*jshint maxstatements:99*/
        "use strict";
        // phantom args
        var sysargs = require('system').args;
        var phantomArgs = [];
        // don't take the first value; this mimics the contents of the old phantom.args
        for (var i = 1; i < sysargs.length; i++) {
            phantomArgs.push(sysargs[i]);
        }
    
        if (phantom.casperLoaded) {
            return;
        }
    
        function __die(message) {
            if (message) {
                console.error(message);
            }
            phantom.exit(1);
        }
    
        function __terminate(message) {
            if (message) {
                console.log(message);
            }
            phantom.exit();
        }
    
        (function (version) {
            // required version check
            if (version.major === 1) {
                if (version.minor < 8) {
                    return __die('CasperJS needs at least PhantomJS v1.8 or later.');
                }
                if (version.minor === 8 && version.patch < 1) {
                    return __die('CasperJS needs at least PhantomJS v1.8.1 or later.');
                }
            } else if (version.major === 2) {
                console.log("Warning PhantomJS v2.0 not yet released. There will not be any official support for any bugs until stable version is released!");
            }
            else return __die('CasperJS needs PhantomJS v1.x or v2.x');
        })(phantom.version);
    
        // Hooks in default phantomjs error handler
        phantom.onError = function onPhantomError(msg, trace) {
            phantom.defaultErrorHandler.apply(phantom, arguments);
            // print a hint when a possible casperjs command misuse is detected
            if (msg.indexOf("ReferenceError: Can't find variable: casper") === 0) {
                console.error('Hint: you may want to use the `casperjs test` command.');
            }
            // exits on syntax error
            if (msg.indexOf('SyntaxError: Parse error') === 0) {
                __die();
            }
        };
    
        // Patching fs
        var fs = (function patchFs(fs) {
            if (!fs.hasOwnProperty('basename')) {
                fs.basename = function basename(path) {
                    return path.replace(/.*\//, '');
                };
            }
            if (!fs.hasOwnProperty('dirname')) {
                fs.dirname = function dirname(path) {
                    if (!path) return undefined;
                    return path.toString().replace(/\\/g, '/').replace(/\/[^\/]*$/, '');
                };
            }
            if (!fs.hasOwnProperty('isWindows')) {
                fs.isWindows = function isWindows() {
                    var testPath = arguments[0] || this.workingDirectory;
                    return (/^[a-z]{1,2}:/i).test(testPath) || testPath.indexOf("\\\\") === 0;
                };
            }
            if (fs.hasOwnProperty('joinPath')) {
                fs.pathJoin = fs.joinPath;
            } else if (!fs.hasOwnProperty('pathJoin')) {
                fs.pathJoin = function pathJoin() {
                    return Array.prototype.join.call(arguments, '/');
                };
            }
            return fs;
        })(require('fs'));
    
        // CasperJS root path
        if (!phantom.casperPath) {
            try {
                phantom.casperPath = phantomArgs.map(function _map(arg) {
                    var match = arg.match(/^--casper-path=(.*)/);
                    if (match) {
                        return fs.absolute(match[1]);
                    }
                }).filter(function _filter(path) {
                    return fs.isDirectory(path);
                }).pop();
            } catch (e) {
                return __die("Couldn't find nor compute phantom.casperPath, exiting.");
            }
        }
    
        /**
         * Prints CasperJS help.
         */
        function printHelp() {
            var engine = phantom.casperEngine === 'slimerjs' ? slimer : phantom;
            var version = [engine.version.major, engine.version.minor, engine.version.patch].join('.');
            return __terminate([
                'CasperJS version ' + phantom.casperVersion.toString() +
                ' at ' + phantom.casperPath + ', using ' + phantom.casperEngine + ' version ' + version,
                fs.read(fs.pathJoin(phantom.casperPath, 'bin', 'usage.txt'))
            ].join('\n'))
        }
    
        /**
         * Patched require to allow loading of native casperjs modules.
         * Every casperjs module have to first call this function in order to
         * load a native casperjs module:
         *
         *     var require = patchRequire(require);
         *     var utils = require('utils');
         *
         * Useless for SlimerJS
         */
        function patchRequire(require) {
            if (require.patched) {
                return require;
            }
            function fromPackageJson(module, dir) {
                var pkgPath, pkgContents, pkg;
                pkgPath = fs.pathJoin(dir, module, 'package.json');
                if (!fs.exists(pkgPath)) {
                    return;
                }
                pkgContents = fs.read(pkgPath);
                if (!pkgContents) {
                    return;
                }
                try {
                    pkg = JSON.parse(pkgContents);
                } catch (e) {
                    return;
                }
                if (typeof pkg === "object" && pkg.main) {
                    return fs.absolute(fs.pathJoin(dir, module, pkg.main));
                }
            }
            function resolveFile(path, dir) {
                var extensions = ['js', 'coffee', 'json'];
                var basenames = [path, path + '/index'];
                var paths = [];
                var nodejsScript = fromPackageJson(path, dir);
                if (nodejsScript) {
                    return nodejsScript;
                }
                basenames.forEach(function(basename) {
                    paths.push(fs.absolute(fs.pathJoin(dir, basename)));
                    extensions.forEach(function(extension) {
                        paths.push(fs.absolute(fs.pathJoin(dir, [basename, extension].join('.'))));
                    });
                });
                for (var i = 0; i < paths.length; i++) {
                    if (fs.isFile(paths[i])) {
                        return paths[i];
                    }
                }
                return null;
            }
            function getCurrentScriptRoot() {
                if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
                    return phantom.casperScriptBaseDir;
                }
                return fs.absolute(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
            }
            function casperBuiltinPath(path) {
                return resolveFile(path, fs.pathJoin(phantom.casperPath, 'modules'));
            }
            function nodeModulePath(path) {
                var resolved, prevBaseDir;
                var baseDir = getCurrentScriptRoot();
                do {
                    resolved = resolveFile(path, fs.pathJoin(baseDir, 'node_modules'));
                    prevBaseDir = baseDir;
                    baseDir = fs.absolute(fs.pathJoin(prevBaseDir, '..'));
                } while (!resolved && baseDir !== '/' && baseDir !== prevBaseDir);
                return resolved;
            }
            function localModulePath(path) {
                return resolveFile(path, phantom.casperScriptBaseDir || fs.workingDirectory);
            }
            var patchedRequire = function patchedRequire(path) {
                try {
                    return require(casperBuiltinPath(path) ||
                                   nodeModulePath(path)    ||
                                   localModulePath(path)   ||
                                   path);
                } catch (e) {
                    throw new CasperError("Can't find module " + path);
                }
            };
            patchedRequire.cache = require.cache;
            patchedRequire.extensions = require.extensions;
            patchedRequire.stubs = require.stubs;
            patchedRequire.patched = true;
            return patchedRequire;
        }
    
        /**
         * Initializes the CasperJS Command Line Interface.
         */
        function initCasperCli(casperArgs) {
            /* jshint maxcomplexity:99 */
            var baseTestsPath = fs.pathJoin(phantom.casperPath, 'tests');
    
            function setScriptBaseDir(scriptName) {
                var dir = fs.dirname(scriptName);
                if (dir === scriptName) {
                    dir = '.';
                }
                phantom.casperScriptBaseDir = dir;
            }
    
            if (!!casperArgs.options.version) {
                return __terminate(phantom.casperVersion.toString())
            } else if (casperArgs.get(0) === "test") {
                phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js'));
                phantom.casperTest = true;
                casperArgs.drop("test");
                setScriptBaseDir(casperArgs.get(0));
            } else if (casperArgs.get(0) === "selftest") {
                phantom.casperScript = fs.absolute(fs.pathJoin(baseTestsPath, 'run.js'));
                phantom.casperSelfTest = phantom.casperTest = true;
                casperArgs.options.includes = fs.pathJoin(baseTestsPath, 'selftest.js');
                if (casperArgs.args.length <= 1) {
                    casperArgs.args.push(fs.pathJoin(baseTestsPath, 'suites'));
                }
                casperArgs.drop("selftest");
                phantom.casperScriptBaseDir = fs.dirname(casperArgs.get(1) || fs.dirname(phantom.casperScript));
            } else if (casperArgs.args.length === 0 || !!casperArgs.options.help) {
                return printHelp();
            }
    
            if (!phantom.casperScript) {
                phantom.casperScript = casperArgs.get(0);
            }
    
            if (phantom.casperScript !== "/dev/stdin" && !fs.isFile(phantom.casperScript)) {
                return __die('Unable to open file: ' + phantom.casperScript);
            }
    
            if (!phantom.casperScriptBaseDir) {
                setScriptBaseDir(phantom.casperScript);
            }
    
            // filter out the called script name from casper args
            casperArgs.drop(phantom.casperScript);
        }
    
        // CasperJS version, extracted from package.json - see http://semver.org/
        phantom.casperVersion = (function getCasperVersion(path) {
            var parts, patchPart, pkg, pkgFile;
            pkgFile = fs.absolute(fs.pathJoin(path, 'package.json'));
            if (!fs.exists(pkgFile)) {
                throw new CasperError('Cannot find package.json at ' + pkgFile);
            }
            try {
                pkg = JSON.parse(require('fs').read(pkgFile));
            } catch (e) {
                throw new CasperError('Cannot read package file contents: ' + e);
            }
            parts  = pkg.version.trim().split(".");
            if (parts.length < 3) {
                throw new CasperError("Invalid version number");
            }
            patchPart = parts[2].split('-');
            return {
                major: ~~parts[0]       || 0,
                minor: ~~parts[1]       || 0,
                patch: ~~patchPart[0]   || 0,
                ident: patchPart[1]     || "",
                toString: function toString() {
                    var version = [this.major, this.minor, this.patch].join('.');
                    if (this.ident) {
                        version = [version, this.ident].join('-');
                    }
                    return version;
                }
            };
        })(phantom.casperPath);
    
        if ("paths" in global.require) {
            // declare a dummy patchRequire function
            global.patchRequire = function(req) {return req;};
    
            require.paths.push(fs.pathJoin(phantom.casperPath, 'modules'));
            require.paths.push(fs.workingDirectory);
        } else {
            global.__require = require;
            global.patchRequire = patchRequire; // must be called in every casperjs module as of 1.1
            global.require = patchRequire(global.require);
        }
    
        if ("slimer" in global) {
            require.globals.patchRequire = global.patchRequire;
            require.globals.CasperError = CasperError;
            phantom.casperEngine = "slimerjs";
        } else {
            phantom.casperEngine = "phantomjs";
        }
    
        // casper cli args
        phantom.casperArgs = require('cli').parse(phantomArgs);
    
        if (true === phantom.casperArgs.get('cli')) {
            initCasperCli(phantom.casperArgs);
        }
    
        if ("paths" in global.require) {
            if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
                require.paths.push(phantom.casperScriptBaseDir);
            } else {
                require.paths.push(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
            }
            require.paths.push(fs.pathJoin(require.paths[require.paths.length-1], 'node_modules'));
        }
    
        // casper loading status flag
        phantom.casperLoaded = true;
    
        // passed casperjs script execution
        if (phantom.casperScript && !phantom.injectJs(phantom.casperScript)) {
            return __die('Unable to load script ' + phantom.casperScript + '; check file syntax');
        }
    })(this, phantom);
    
    
    • Public Snippets
    • Channels Snippets