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

use*_*003 24 javascript phantomjs

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

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

console.log('some stuff I wrote');
Run Code Online (Sandbox Code Playgroud)

这不是那么有用.

Aru*_*run 42

以下内容可以通过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();
Run Code Online (Sandbox Code Playgroud)

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

Refused to display document because display forbidden by X-Frame-Options.
Run Code Online (Sandbox Code Playgroud)


use*_*003 15

所以我明白了:

>phantomjs.exe file_to_run.js > my_log.txt
Run Code Online (Sandbox Code Playgroud)

  • 虽然这有效,但它也会将可能不需要的内容写入文件,例如javascripts错误和其他phantomjs错误.你最好用Arun的答案,这样你就可以完全控制*写的东西. (11认同)
  • 不使用phantomjs写入文件.这只是标准的stdout重定向,因此不是问题的答案. (6认同)

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

然后你可以这样做:

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