24

从 PhantomJS,我如何写入日志而不是控制台?

在示例https://github.com/ariya/phantomjs/wiki/Examples中,它总是(在我看过的示例中)说的是:

console.log('some stuff I wrote');

这不是那么有用。

4

3 回答 3

43

下面可以通过phantomjs直接将内容写入文件:

var fs = require('fs');
   try {
    fs.write("/home/username/sampleFileName.txt", "Message to be written to the file", 'w');
    } catch(e) {
        console.log(e);
    }
    phantom.exit();

当出现一些警告或异常时,user984003 的答案中的命令会失败。有时不符合我们的特定要求,因为在某些代码库中,我总是收到以下消息,该消息也将记录到该文件中。

Refused to display document because display forbidden by X-Frame-Options.
于 2013-07-25T11:34:02.443 回答
16

所以我想通了:

>phantomjs.exe file_to_run.js > my_log.txt
于 2013-03-27T08:46:37.507 回答
10

您可以覆盖原来的 console.log 功能,看看这个:

Object.defineProperty(console, "toFile", {
    get : function() {
        return console.__file__;
    },
    set : function(val) {
        if (!console.__file__ && val) {
            console.__log__ = console.log;
            console.log = function() {
                var fs = require('fs');
                var msg = '';
                for (var i = 0; i < arguments.length; i++) {
                    msg += ((i === 0) ? '' : ' ') + arguments[i];
                }
                if (msg) {
                    fs.write(console.__file__, msg + '\r\n', 'a');
                }
            };
        }
        else if (console.__file__ && !val) {
            console.log = console.__log__;
        }
        console.__file__ = val;
    }
});

然后你可以这样做:

console.log('this will go to console');
console.toFile = 'test.txt';
console.log('this will go to the test.txt file');
console.toFile = '';
console.log('this will again go to the console');
于 2015-05-22T15:27:55.360 回答