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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With