【发布时间】:2014-07-11 17:12:26
【问题描述】:
我需要在 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);
}
});
这段代码似乎在 Windows 7、x86 机器上运行良好,phantomjs 版本为 1.9.7,
$ 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
【问题讨论】:
-
无法重现:您是否真的在脚本所在的文件夹中通过
npm install colors安装了颜色?它不适用于全局,因为 phantomjs 不使用 npm 存储库。 -
是的,我已经做到了。
-
你试过像
require('./node_modules/colors/colors.js')这样直接要求吗? -
没有。返回相同的错误
Unknown module ./node_modules/colors/colors.js for require() -
另见stackoverflow.com/a/24388906/841830(它适用于回答者,但不适用于我在Linux上,所以我现在很好奇他是否使用Windows,问题就在那里......但是我猜这个问题与我设置 npm 的方式有关。)