Search code examples
javascriptphantomjscasperjs

How to make a custom CasperJS module with custom parameter?


FileUtil.js:

exports.a = function(pre) {
    var module = {}

    module.writeStringToFile = function writeStringToFile() {
        casper.log(pre + " succ");
    };

    return module
}

main.js:

var casper = require('casper').create();
var FileUtil = require('FileUtil').a('xxx')
FileUtil.writeStringToFile() //xxx succ

That works, but what I want is var FileUtil = require('FileUtil')('xxx') instead of require('FileUtil').a('xxx').

I tried exports = function(pre) ..., but it doesn't works.

So, how to make a custom CasperJS module with custom parameter?


Solution

  • If you want var FileUtil = require('FileUtil')('xxx') to be your object then you need to use module.exports. It can export a single object, which can even be a function:

    module.exports = function(pre) {
        var module = {}
    
        module.writeStringToFile = function writeStringToFile() {
            casper.log(pre + " succ");
        };
    
        return module
    }
    

    Of course, it would be a better form to rename the inner module variable to something else.