如何在CasperJS中获取当前执行的文件目录

Val*_*sin 13 phantomjs casperjs

我正在使用CasperJS检查一些站点并将JSON数据写入文件.文件应写入public/data文件夹.但是当我试图casperjs 在我的项目目录(例如我的主目录)之外调用时,它直接写入文件~/public/data,而不是在我的项目目录中.

我该怎么解决这个问题?我还没有找到如何获取__dirname或__filename.

Mor*_*gon 20

我有这个问题; 需要相对于脚本所在位置的路径中的文件.通过一点点(阅读:大量)修补,我能够产生以下内容:

// 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('/'));
}
Run Code Online (Sandbox Code Playgroud)

这允许我fs.read()spawn文件使用相对路径.也许require(),我只是没有一个模块来测试它.

希望这有用!

  • 这显然需要`var fs = require('fs');` (2认同)

Hem*_*ela 2

您可以使用phantomJS的文件系统模块。

由于 CasperJS 是基于 PhantomJS 构建的,因此您可以将 Phantom 的模块包含在 CasperJS 脚本中。

尝试:

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

有关文件系统模块的完整文档请参见此处