Reputation: 5237
How I can write result inside page.evaluate to file? This code works fine when putting results into console.log, but writing to file, using ts
raising errors.
page.evaluate(function(url) {
function getHTTPResponseString(url, callback) {
try {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status == 200) {
var u8 = new Uint8Array(this.response), bs = [];
for (var i = u8.length - 1; i >= 0; --i) {
bs[i] = String.fromCharCode(u8[i]);
}
callback(bs.join(''));
} else {
console.log(this.statusText);
callback('');
}
}
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.send();
} catch (e) {
console.log(JSON.stringify(e));
}
}
getHTTPResponseString(url, function(result) {
console.log(result);
})
}, url);
Upvotes: 2
Views: 968
Reputation: 5237
I found that it's possible to pass data by calling window.callphantom()
inside of page.evaluate
and next handle passed data by page.onCallback
event:
page.onCallback = function(result) {
var fs = require('fs');
fs.write('file.out', result, 'w');
};
getHTTPResponseString(url, function(result) {
console.log(result);
window.callPhantom(result);
})
Upvotes: 4
Reputation: 16856
One can't write to file from inside of page.evaluate() function, as it's working in browser context where there is no access to local filesystem.
However you can return data you want to analyze and then deal with it on PhantomJS side.
var error = page.evaluate(function(url) {
// ...
return xhr.statusText;
}, url);
fs.write(filename, error, 'a');
Perhaps a simpler way to log data is to subscribe to console messages from browser context with page.onConsoleMessage function:
page.onConsoleMessage = function (msg) {
console.log("Browser console: " + msg);
};
There's also a page.onError function to listen for errors that happen inside page.evaluate: http://phantomjs.org/api/webpage/handler/on-error.html
Upvotes: 1