PhantomJS / Javascript:写入文件而不是控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15654283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PhantomJS / Javascript: write to file instead of to console
提问by user984003
From PhantomJS, how do I write to a log instead of to the console?
从 PhantomJS,我如何写入日志而不是控制台?
In the examples https://github.com/ariya/phantomjs/wiki/Examples, it always (in the ones I have looked at) says something like:
在示例https://github.com/ariya/phantomjs/wiki/Examples 中,它总是(在我看过的那些)中说:
console.log('some stuff I wrote');
This is not so useful.
这不是很有用。
采纳答案by user984003
So I figured it out:
所以我想通了:
>phantomjs.exe file_to_run.js > my_log.txt
回答by Arun
The following can write contents to the file directly by phantomjs:
以下可以通过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.
user984003 回答中的命令在出现警告或异常时失败。有时不符合我们的特定要求,因为在某些代码库中,我总是收到以下消息,这些消息也将记录到该文件中。
Refused to display document because display forbidden by X-Frame-Options.
回答by Ivan
You can override original console.log function, take a look at this :
您可以覆盖原来的 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;
}
});
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');