PhantomJS / Javascript:写入文件而不是控制台

时间:2013-03-27 08:14:58

标签: javascript phantomjs

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

在示例https://github.com/ariya/phantomjs/wiki/Examples中,它总是(在我看过的那些)中说出如下内容:

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

这不太有用。

3 个答案:

答案 0 :(得分:41)

以下内容可以直接通过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.

答案 1 :(得分:14)

所以我明白了:

>phantomjs.exe file_to_run.js > my_log.txt

答案 2 :(得分: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');
相关问题