I had this exact issue; requiring a file in a path relative to where the script lived.
With a little (read: a lot of) tinkering, I was able to produce the following:
// Since Casper has control, the invoked script is deep in the argument stack
const args = require('system').args;
var currentFile = args[args.length - 1];
var curFilePath = fs.absolute(currentFile).split('/');
// I only bother to change the directory if we weren't already there when invoking casperjs
if (curFilePath.length > 1) {
curFilePath.pop(); // PhantomJS does not have an equivalent path.baseName()-like method
fs.changeWorkingDirectory(curFilePath.join('/'));
}
This allows me to fs.read()
and spawn
files using relative paths. Perhaps require()
as well, I just didn't have a module to test it with.
Hope this is helpful!