user984003
user984003

Reputation: 29569

PhantomJS / Javascript: write to file instead of to console

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 at) says something like:

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

This is not so useful.

Upvotes: 24

Views: 22680

Answers (3)

Ivan
Ivan

Reputation: 186

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

Upvotes: 10

Arun
Arun

Reputation: 2572

The following can write contents to the file directly by 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();

The command in the answer by user984003 fails when there is some warning or exceptions occurred. And sometimes does not fall into our specific requirements because in some codebase I am getting the following message always which will also be logged to that file.

Refused to display document because display forbidden by X-Frame-Options.

Upvotes: 43

user984003
user984003

Reputation: 29569

So I figured it out:

>phantomjs.exe file_to_run.js > my_log.txt

Upvotes: 17

Related Questions