PhantomJS / [removed] write to file instead of to console

前端 未结 3 1690
遥遥无期
遥遥无期 2021-02-01 04:45

From PhantomJS, how do I write to a log instead of to the console?

In the examples https://github.com/ariya/phantomjs/wiki/Examples, it always (in the ones I have looked

3条回答
  •  醉梦人生
    2021-02-01 05:12

    You can override original console.log function, take a look at this :

    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;
        }
    });
    

    Then you can do this:

    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');
    

提交回复
热议问题