Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get currently executed file directory in CasperJS

I'm using CasperJS to check some site and write JSON data into a file. File should be written into public/data folder. But when I'm trying to call casperjs outside of my project directory (e.g. my home directory), it writes file directly in ~/public/data, not in my project directory.

How should I solve this? I haven't found how to get __dirname or __filename.

like image 963
ValeriiVasin Avatar asked May 27 '13 08:05

ValeriiVasin


1 Answers

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!

like image 96
Morgon Avatar answered Sep 28 '22 07:09

Morgon