我需要使用phantomjs颜色(或类似的npm模块,欢迎建议)。这是我的代码:
var page = require('webpage').create();
var url = require('system').args[1];
var fs = require('fs');
var colors = require('colors');
console.log(">>In Phantomjs Process...".yellow);
page.open(url, function (status) {
if (status !== 'success') {
console.log(">>Error Opening Webpage.".red);
phantom.exit();
}
else {
console.log(">>Page Loaded Successfully...".yellow);
window.setTimeout(function () {
fs.write('index.txt', page.content, 'w');
phantom.exit();
}, 10000);
}
});
此代码似乎在带有phantomjs版本1.9.7的Windows 7 x86机器上正常运行,
$ phantomjs fetchDOM.js "http://www.google.com"
>>In Phantom Process...
>>Page Loaded Successfully...
但是在使用phantomjs版本1.9.7的Ubuntu 13.04 x86机器上,
$ phantomjs fetchDOM.js "http://www.google.com"
Unknown module colors for require()
为什么会这样?这有什么解决方法吗?提前谢谢。
颜色模块文档可在此处找到:https://www.npmjs.org/package/colors
编辑:如果我将var colors = require('colors');
替换为phantom.injectJs('colors');
,则错误消失,但输出不符合预期。
$ phantomjs fetchDOM.js "http://www.google.com"
undefined
undefined
答案 0 :(得分:0)
问题是PhantomJS中没有process
API。我通过修改support-colors.js
/colors/lib/system/supports-colors.js
来修复它
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var system = require('system');
var argv = system.args;
var env = system.env;
var os = system.os;
module.exports = (function () {
if (argv.indexOf('--no-color') !== -1 ||
argv.indexOf('--color=false') !== -1) {
return false;
}
if (argv.indexOf('--color') !== -1 ||
argv.indexOf('--color=true') !== -1 ||
argv.indexOf('--color=always') !== -1) {
return true;
}
//if (process.stdout && !process.stdout.isTTY) {
// return false;
//}
if (os.architecture === 'win32' && os.name === 'windows') {
return true;
}
if ('COLORTERM' in env) {
return true;
}
if (env['TERM'] === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(env['TERM'])) {
return true;
}
return false;
})();