13

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.

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
ValeriiVasin
  • 8,628
  • 11
  • 58
  • 78

5 Answers5

20

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!

Vic Seedoubleyew
  • 9,888
  • 6
  • 55
  • 76
Morgon
  • 3,269
  • 1
  • 27
  • 32
2

You can use FileSystem module of phantomJS.

Because CasperJS was built over PhantomJS, you can include Phantom's modules inside your CasperJS Scripts.

Try:

//require a reference to the fs module
var fs = require('fs');
...
//changes the current workingDirectory to the specified path.
fs.changeWorkingDirectory('/your/path')

Full documentation about FileSystem Module here

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Hemerson Varela
  • 24,034
  • 16
  • 68
  • 69
2

My solution:

var system = require('system')
var absoluteFilePath = system.args[4];
var absoluteFileDir = absoluteFilePath.replace('{your_file_name}', '');

To check system args:

console.log(system.args)
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Tomas Romero
  • 8,418
  • 11
  • 50
  • 72
1

All that you need is to use phantomjs fs:

Basically you can set on your project as full path:

var fs = require('fs');
console.log(fs.workingDirectory);
// output "F:/path/to/your/project"
onalbi
  • 2,609
  • 1
  • 24
  • 36
0

You give an answer for a specific casperjs call with 4 arguments. The general solution is to take the last argument as absoluteFilePath

var system = require('system')
var absoluteFilePath = system.args[system.args.length-1];
var absoluteFileDir = absoluteFilePath.replace('{your_file_name}', '');
Kruskaal
  • 77
  • 8