Commit 5f399561 by mawei

add horseman module

parent 94b811fc
...@@ -2,10 +2,11 @@ ...@@ -2,10 +2,11 @@
process.env.NODE_CONFIG_DIR = '../config'; process.env.NODE_CONFIG_DIR = '../config';
const fs = require('fs'); const fs = require('fs');
const redis = require("redis");
const config = require('config'); const config = require('config');
const phantom = require('phantom'); const phantom = require('phantom');
const cheerio = require('cheerio'); const cheerio = require('cheerio');
const redis = require("redis"); var Horseman = require('node-horseman');
const Promise = require('bluebird'); const Promise = require('bluebird');
const captcha = require('../captcha'); const captcha = require('../captcha');
...@@ -67,37 +68,47 @@ class AutoHome { ...@@ -67,37 +68,47 @@ class AutoHome {
try { try {
const username = this.params.username; const username = this.params.username;
const password = this.params.password; const password = this.params.password;
const instance = await phantom.create(['--ignore-ssl-errors=yes']);
const page = await instance.createPage();
page.property('viewportSize', {width: 1920, height: 1080});
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});
const status = await page.open('http://ics.autohome.com.cn/passport/Home/Index');
console.log('主页:', status);
page.render('m1.png');
const content = await page.property('content');
const $ = cheerio.load(content);
// 验证码裁剪
page.property('clipRect', { top: 313, left: 1430, width: 64, height: 27 });
const base64Text = await page.renderBase64('PNG');
// 验证码存储到磁盘 const horseman = new Horseman();
horseman
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.viewport(1920, 1080)
.on('onResourceRequested', (requestData, networkRequest) => {
console.info('Requesting', requestData.url);
})
.open('http://ics.autohome.com.cn/passport/Home/Index')
.screenshot('m1.png')
.crop('#imgValidCodeDealer', 'm2.png')
.cropBase64('#imgValidCodeDealer', 'PNG')
.then((base64Text) => {
return base64Text;
}).then((base64Text) => {
// const imageFile = 'tmp/' + (new Date) . getTime() + '.gif'; // const imageFile = 'tmp/' + (new Date) . getTime() + '.gif';
const imageFile = 'm2.png'; const imageFile = 'm5.png';
const writeStream = fs.createWriteStream(imageFile); const writeStream = fs.createWriteStream(imageFile);
// data:image/png;base64, + base64Text // data:image/png;base64, + base64Text
await writeStream.write(base64Text, 'base64'); writeStream.write(base64Text, 'base64');
}).then(() => {
const captchaType = config.get('Dealer')[this.name]['captchaType']; const captchaType = config.get('Dealer')[this.name]['captchaType'];
const captchaText = captcha.decode(captchaType, imageFile);
// 验证码解码
const captchaText = await captcha.decode(captchaType, imageFile);
console.info('imageFile:', imageFile); console.info('imageFile:', imageFile);
console.info('captchaText:', captchaText); console.info('captchaText:', captchaText);
})
// .type('input[name="q"]', 'github')
// .click('[name="btnK"]')
// .keyboardEvent('keypress', 16777221)
// .waitForSelector('div.g')
// .count('div.g')
// .log() // prints out the number of results
.close();
return;
// 验证码存储到磁盘
// 验证码解码
// 填写登录表单 // 填写登录表单
page.evaluate(function(username, password, captchaTxt) { page.evaluate(function(username, password, captchaTxt) {
......
'use strict';
process.env.NODE_CONFIG_DIR = '../config';
const fs = require('fs');
const config = require('config');
const phantom = require('phantom');
const cheerio = require('cheerio');
const redis = require("redis");
const Promise = require('bluebird');
const captcha = require('../captcha');
Promise.promisifyAll(redis);
Promise.promisifyAll(fs);
class AutoHome {
constructor(params) {
this.name = 'autohome';
this.params = params;
console.log(params);
}
execute() {
return new Promise((resolve, reject) => {
switch (this.params.task) {
case 'login': {
console.log('do login');
this.login();
break;
}
case 'tryLogin': {
console.log('do login');
this.tryLogin();
break;
}
}
});
}
async tryLogin() {
try {
const client = await redis.createClient();
const cookies_key = this.name + '_cookies';
const cookies = await client.getAsync(cookies_key);
await client.quit();
console.log(JSON.decode(cookies));
} catch (e) {
throw e;
}
const instance = await phantom.create(['--ignore-ssl-errors=yes']);
const page = await instance.createPage();
page.property('viewportSize', {width: 1920, height: 1080});
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});
const status = await page.open('http://ics.autohome.com.cn/passport/Home/Index');
console.log(status);
// data:image/png;base64, + baseTxt
await page.render('m5.png');
await instance.exit();
}
async login() {
try {
const username = this.params.username;
const password = this.params.password;
const instance = await phantom.create(['--ignore-ssl-errors=yes']);
const page = await instance.createPage();
page.property('viewportSize', {width: 1920, height: 1080});
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});
const status = await page.open('http://ics.autohome.com.cn/passport/Home/Index');
console.log('主页:', status);
page.render('m1.png');
const content = await page.property('content');
const $ = cheerio.load(content);
// 验证码裁剪
page.property('clipRect', { top: 313, left: 1430, width: 64, height: 27 });
const base64Text = await page.renderBase64('PNG');
// 验证码存储到磁盘
// const imageFile = 'tmp/' + (new Date) . getTime() + '.gif';
const imageFile = 'm2.png';
const writeStream = fs.createWriteStream(imageFile);
// data:image/png;base64, + base64Text
await writeStream.write(base64Text, 'base64');
const captchaType = config.get('Dealer')[this.name]['captchaType'];
// 验证码解码
const captchaText = await captcha.decode(captchaType, imageFile);
console.info('imageFile:', imageFile);
console.info('captchaText:', captchaText);
// 填写登录表单
page.evaluate(function(username, password, captchaTxt) {
$('#UserNameDealer').val(username);
$('#PasswordDealer').val(password);
$('#checkCodeDealer').val(captchaTxt);
$('#btnDealer').trigger('click');
}, username, password, captchaText);
page.property('clipRect', { top: 0, left: 0, width: 1920, height: 1080 });
await Promise.delay(2000);
await page.render('m3.png');
const cookies = await page.cookies();
const cookie_key = this.name + '_cookie';
const client = await redis.createClient();
client.set(cookie_key, JSON.stringify(cookies), redis.print);
client.quit();
console.info('cookie保存成功');
// await instance.exit();
} catch (e) {
throw e;
}
}
}
module.exports = AutoHome;
\ No newline at end of file
m1.png

713 KB

m2.png

4.92 KB

m5.png

4.92 KB

All packages installed at Fri Aug 04 2017 18:58:04 GMT+0800 (CST) All packages installed at Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file \ No newline at end of file
Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
language: node_js
node_js:
- 0.10
Copyright © 2011-2015 Paul Vorbach <paul@vorba.ch>
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, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# clone
[![build status](https://secure.travis-ci.org/pvorb/node-clone.png)](http://travis-ci.org/pvorb/node-clone)
[![info badge](https://nodei.co/npm/clone.png?downloads=true&downloadRank=true&stars=true)](http://npm-stat.com/charts.html?package=clone)
offers foolproof _deep cloning_ of objects, arrays, numbers, strings etc. in JavaScript.
## Installation
npm install clone
(It also works with browserify, ender or standalone.)
## Example
~~~ javascript
var clone = require('clone');
var a, b;
a = { foo: { bar: 'baz' } }; // initial value of a
b = clone(a); // clone a -> b
a.foo.bar = 'foo'; // change a
console.log(a); // show a
console.log(b); // show b
~~~
This will print:
~~~ javascript
{ foo: { bar: 'foo' } }
{ foo: { bar: 'baz' } }
~~~
**clone** masters cloning simple objects (even with custom prototype), arrays,
Date objects, and RegExp objects. Everything is cloned recursively, so that you
can clone dates in arrays in objects, for example.
## API
`clone(val, circular, depth)`
* `val` -- the value that you want to clone, any type allowed
* `circular` -- boolean
Call `clone` with `circular` set to `false` if you are certain that `obj`
contains no circular references. This will give better performance if needed.
There is no error if `undefined` or `null` is passed as `obj`.
* `depth` -- depth to which the object is to be cloned (optional,
defaults to infinity)
`clone.clonePrototype(obj)`
* `obj` -- the object that you want to clone
Does a prototype clone as
[described by Oran Looney](http://oranlooney.com/functional-javascript/).
## Circular References
~~~ javascript
var a, b;
a = { hello: 'world' };
a.myself = a;
b = clone(a);
console.log(b);
~~~
This will print:
~~~ javascript
{ hello: "world", myself: [Circular] }
~~~
So, `b.myself` points to `b`, not `a`. Neat!
## Test
npm test
## Caveat
Some special objects like a socket or `process.stdout`/`stderr` are known to not
be cloneable. If you find other objects that cannot be cloned, please [open an
issue](https://github.com/pvorb/node-clone/issues/new).
## Bugs and Issues
If you encounter any bugs or issues, feel free to [open an issue at
github](https://github.com/pvorb/node-clone/issues) or send me an email to
<paul@vorba.ch>. I also always like to hear from you, if you’re using my code.
## License
Copyright © 2011-2015 [Paul Vorbach](http://paul.vorba.ch/) and
[contributors](https://github.com/pvorb/node-clone/graphs/contributors).
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, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var clone = (function() {
'use strict';
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
*/
function clone(parent, circular, depth, prototype) {
var filter;
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
filter = circular.filter;
circular = circular.circular
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth == 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (clone.__isArray(parent)) {
child = [];
} else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
child = new Buffer(parent.length);
parent.copy(child);
return child;
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
};
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
};
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
};
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
};
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global) flags += 'g';
if (re.ignoreCase) flags += 'i';
if (re.multiline) flags += 'm';
return flags;
};
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if (typeof module === 'object' && module.exports) {
module.exports = clone;
}
{
"name": "clone",
"description": "deep cloning of objects and arrays",
"tags": [
"clone",
"object",
"array",
"function",
"date"
],
"version": "1.0.2",
"repository": {
"type": "git",
"url": "git://github.com/pvorb/node-clone.git"
},
"bugs": {
"url": "https://github.com/pvorb/node-clone/issues"
},
"main": "clone.js",
"author": "Paul Vorbach <paul@vorba.ch> (http://paul.vorba.ch/)",
"contributors": [
"Blake Miner <miner.blake@gmail.com> (http://www.blakeminer.com/)",
"Tian You <axqd001@gmail.com> (http://blog.axqd.net/)",
"George Stagas <gstagas@gmail.com> (http://stagas.com/)",
"Tobiasz Cudnik <tobiasz.cudnik@gmail.com> (https://github.com/TobiaszCudnik)",
"Pavel Lang <langpavel@phpskelet.org> (https://github.com/langpavel)",
"Dan MacTough (http://yabfog.com/)",
"w1nk (https://github.com/w1nk)",
"Hugh Kennedy (http://twitter.com/hughskennedy)",
"Dustin Diaz (http://dustindiaz.com)",
"Ilya Shaisultanov (https://github.com/diversario)",
"Nathan MacInnes <nathan@macinn.es> (http://macinn.es/)",
"Benjamin E. Coe <ben@npmjs.com> (https://twitter.com/benjamincoe)",
"Nathan Zadoks (https://github.com/nathan7)",
"Róbert Oroszi <robert+gh@oroszi.net> (https://github.com/oroce)",
"Aurélio A. Heckert (http://softwarelivre.org/aurium)",
"Guy Ellis (http://www.guyellisrocks.com/)"
],
"license": "MIT",
"engines": {
"node": ">=0.8"
},
"dependencies": {},
"devDependencies": {
"nodeunit": "~0.9.0"
},
"optionalDependencies": {},
"scripts": {
"test": "nodeunit test.js"
},
"_from": "clone@1.0.2",
"_resolved": "http://registry.npm.taobao.org/clone/download/clone-1.0.2.tgz"
}
\ No newline at end of file
<html>
<head>
<meta charset="utf-8">
<title>Clone Test-Suite (Browser)</title>
</head>
<body>
<script>
var data = document.location.search.substr(1).split('&');
try {
ctx = parent[data[0]];
eval(decodeURIComponent(data[1]));
window.results = results;
} catch(e) {
var extra = '';
if (e.name == 'SecurityError')
extra = 'This test suite needs to be run on an http server.';
alert('Apart Context iFrame Error\n' + e + '\n\n' + extra);
throw e;
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Clone Test-Suite (Browser)</title>
<script>
var module = {};
var tests = exports = module.exports = {};
function require(moduleName) {
if (moduleName == './') {
return clone;
}
}
function log(str) {
logList.innerHTML += '<li>' + str + '</li>';
}
</script>
<script src="clone.js"></script>
<script src="test.js"></script>
</head>
<body>
<h1 id="nodeunit-header">Clone Test-Suite (Browser)</h1>
Tests started: <span id="testsStarted"></span>;
Tests finished: <span id="testsFinished"></span>.
<ul id="logList"></ul>
<script>
/* Methods copied from
* https://github.com/caolan/nodeunit/blob/master/lib/assert.js
*/
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
var _keys = function (obj){
if (Object.keys) return Object.keys(obj);
if (typeof obj != 'object' && typeof obj != 'function') {
throw new TypeError('-');
}
var keys = [];
for(var k in obj) if(obj.hasOwnProperty(k)) keys.push(k);
return keys;
};
function objEquiv(a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
if (a.prototype !== b.prototype)
return false;
if (isArguments(a)) {
if (!isArguments(b)) return false;
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try {
var ka = _keys(a), kb = _keys(b), key, i;
} catch (e) {
return false
}
if (ka.length != kb.length)
return false;
ka.sort();
kb.sort();
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i]) return false;
}
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key] ))
return false;
}
return true;
}
function _deepEqual(actual, expected) {
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
} else if (actual instanceof RegExp && expected instanceof RegExp) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.ignoreCase === expected.ignoreCase &&
actual.multiline === expected.multiline;
} else if (typeof actual != 'object' && typeof expected != 'object') {
return actual == expected;
} else {
return objEquiv(actual, expected);
}
}
for (var testName in tests) {
setTimeout((function (testName) {
try {
testsStarted.innerHTML = (parseInt(testsStarted.innerHTML) || 0) + 1;
function incFinished() {
testsFinished.innerHTML = (parseInt(testsFinished.innerHTML) || 0) + 1;
}
tests[testName]({
expect: function (num) {
this._expect = num
},
ok: function (val) {
if(!val) throw new Error(val + ' is not ok.')
},
equal: function (a,b) {
if (a != b) throw new Error(a + ' is not equal to ' + b)
},
notEqual: function (a,b) {
if (a == b) throw new Error(a + ' is equal to ' + b)
},
strictEqual: function (a,b) {
if (a !== b) throw new Error(a + ' is not strict equal to ' + b)
},
deepEqual: function (a,b) {
if (!_deepEqual(a,b))
throw new Error(JSON.stringify(a) + ' is not deep equal to ' +
JSON.stringify(b))
},
done: function () {
log(testName + ' <span style="color:blue">is ok</span>.');
incFinished();
}
});
} catch(e) {
log(testName + ' <span style="color:red">FAIL.</span> <small>'+ e +'</small>');
incFinished();
console.log(e);
}
})(testName), 1);
}
</script>
</body>
</html>
var clone = require('./');
function inspect(obj) {
seen = [];
return JSON.stringify(obj, function (key, val) {
if (val != null && typeof val == "object") {
if (seen.indexOf(val) >= 0) {
return '[cyclic]';
}
seen.push(val);
}
return val;
});
}
// Creates a new VM in node, or an iframe in a browser in order to run the
// script
function apartContext(context, script, callback) {
var vm = require('vm');
if (vm) {
var ctx = vm.createContext({ ctx: context });
callback(vm.runInContext(script, ctx));
} else if (document && document.createElement) {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
var myCtxId = 'tmpCtx' + Math.random();
window[myCtxId] = context;
iframe.src = 'test-apart-ctx.html?' + myCtxId + '&' + encodeURIComponent(script);
iframe.onload = function() {
try {
callback(iframe.contentWindow.results);
} catch (e) {
throw e;
}
};
} else {
console.log('WARNING: cannot create an apart context.');
}
}
exports["clone string"] = function (test) {
test.expect(2); // how many tests?
var a = "foo";
test.strictEqual(clone(a), a);
a = "";
test.strictEqual(clone(a), a);
test.done();
};
exports["clone number"] = function (test) {
test.expect(5); // how many tests?
var a = 0;
test.strictEqual(clone(a), a);
a = 1;
test.strictEqual(clone(a), a);
a = -1000;
test.strictEqual(clone(a), a);
a = 3.1415927;
test.strictEqual(clone(a), a);
a = -3.1415927;
test.strictEqual(clone(a), a);
test.done();
};
exports["clone date"] = function (test) {
test.expect(3); // how many tests?
var a = new Date;
var c = clone(a);
test.ok(!!a.getUTCDate && !!a.toUTCString);
test.ok(!!c.getUTCDate && !!c.toUTCString);
test.equal(a.getTime(), c.getTime());
test.done();
};
exports["clone object"] = function (test) {
test.expect(1); // how many tests?
var a = { foo: { bar: "baz" } };
var b = clone(a);
test.deepEqual(b, a);
test.done();
};
exports["clone array"] = function (test) {
test.expect(2); // how many tests?
var a = [
{ foo: "bar" },
"baz"
];
var b = clone(a);
test.ok(b instanceof Array);
test.deepEqual(b, a);
test.done();
};
exports["clone buffer"] = function (test) {
if (typeof Buffer == 'undefined') {
return test.done();
}
test.expect(1);
var a = new Buffer("this is a test buffer");
var b = clone(a);
// no underscore equal since it has no concept of Buffers
test.deepEqual(b, a);
test.done();
};
exports["clone regexp"] = function (test) {
test.expect(5);
var a = /abc123/gi;
var b = clone(a);
test.deepEqual(b, a);
var c = /a/g;
test.ok(c.lastIndex === 0);
c.exec('123a456a');
test.ok(c.lastIndex === 4);
var d = clone(c);
test.ok(d.global);
test.ok(d.lastIndex === 4);
test.done();
};
exports["clone object containing array"] = function (test) {
test.expect(1); // how many tests?
var a = {
arr1: [ { a: '1234', b: '2345' } ],
arr2: [ { c: '345', d: '456' } ]
};
var b = clone(a);
test.deepEqual(b, a);
test.done();
};
exports["clone object with circular reference"] = function (test) {
test.expect(8); // how many tests?
var c = [1, "foo", {'hello': 'bar'}, function () {}, false, [2]];
var b = [c, 2, 3, 4];
var a = {'b': b, 'c': c};
a.loop = a;
a.loop2 = a;
c.loop = c;
c.aloop = a;
var aCopy = clone(a);
test.ok(a != aCopy);
test.ok(a.c != aCopy.c);
test.ok(aCopy.c == aCopy.b[0]);
test.ok(aCopy.c.loop.loop.aloop == aCopy);
test.ok(aCopy.c[0] == a.c[0]);
test.ok(eq(a, aCopy));
aCopy.c[0] = 2;
test.ok(!eq(a, aCopy));
aCopy.c = "2";
test.ok(!eq(a, aCopy));
function eq(x, y) {
return inspect(x) === inspect(y);
}
test.done();
};
exports['clone prototype'] = function (test) {
test.expect(3); // how many tests?
var a = {
a: "aaa",
x: 123,
y: 45.65
};
var b = clone.clonePrototype(a);
test.strictEqual(b.a, a.a);
test.strictEqual(b.x, a.x);
test.strictEqual(b.y, a.y);
test.done();
};
exports['clone within an apart context'] = function (test) {
var results = apartContext({ clone: clone },
"results = ctx.clone({ a: [1, 2, 3], d: new Date(), r: /^foo$/ig })",
function (results) {
test.ok(results.a.constructor.toString() === Array.toString());
test.ok(results.d.constructor.toString() === Date.toString());
test.ok(results.r.constructor.toString() === RegExp.toString());
test.done();
});
};
exports['clone object with no constructor'] = function (test) {
test.expect(3);
var n = null;
var a = { foo: 'bar' };
a.__proto__ = n;
test.ok(typeof a === 'object');
test.ok(typeof a !== null);
var b = clone(a);
test.ok(a.foo, b.foo);
test.done();
};
exports['clone object with depth argument'] = function (test) {
test.expect(6);
var a = {
foo: {
bar : {
baz : 'qux'
}
}
};
var b = clone(a, false, 1);
test.deepEqual(b, a);
test.notEqual(b, a);
test.strictEqual(b.foo, a.foo);
b = clone(a, true, 2);
test.deepEqual(b, a);
test.notEqual(b.foo, a.foo);
test.strictEqual(b.foo.bar, a.foo.bar);
test.done();
};
exports['maintain prototype chain in clones'] = function (test) {
test.expect(1);
function T() {}
var a = new T();
var b = clone(a);
test.strictEqual(Object.getPrototypeOf(a), Object.getPrototypeOf(b));
test.done();
};
exports['parent prototype is overriden with prototype provided'] = function (test) {
test.expect(1);
function T() {}
var a = new T();
var b = clone(a, true, Infinity, null);
test.strictEqual(b.__defineSetter__, undefined);
test.done();
};
exports['clone object with null children'] = function (test) {
test.expect(1);
var a = {
foo: {
bar: null,
baz: {
qux: false
}
}
};
var b = clone(a);
test.deepEqual(b, a);
test.done();
};
exports['clone instance with getter'] = function (test) {
test.expect(1);
function Ctor() {};
Object.defineProperty(Ctor.prototype, 'prop', {
configurable: true,
enumerable: true,
get: function() {
return 'value';
}
});
var a = new Ctor();
var b = clone(a);
test.strictEqual(b.prop, 'value');
test.done();
};
exports['get RegExp flags'] = function (test) {
test.strictEqual(clone.__getRegExpFlags(/a/), '' );
test.strictEqual(clone.__getRegExpFlags(/a/i), 'i' );
test.strictEqual(clone.__getRegExpFlags(/a/g), 'g' );
test.strictEqual(clone.__getRegExpFlags(/a/gi), 'gi');
test.strictEqual(clone.__getRegExpFlags(/a/m), 'm' );
test.done();
};
exports["recognize Array object"] = function (test) {
var results = apartContext(null, "results = [1, 2, 3]", function(alien) {
var local = [4, 5, 6];
test.ok(clone.__isArray(alien)); // recognize in other context.
test.ok(clone.__isArray(local)); // recognize in local context.
test.ok(!clone.__isDate(alien));
test.ok(!clone.__isDate(local));
test.ok(!clone.__isRegExp(alien));
test.ok(!clone.__isRegExp(local));
test.done();
});
};
exports["recognize Date object"] = function (test) {
var results = apartContext(null, "results = new Date()", function(alien) {
var local = new Date();
test.ok(clone.__isDate(alien)); // recognize in other context.
test.ok(clone.__isDate(local)); // recognize in local context.
test.ok(!clone.__isArray(alien));
test.ok(!clone.__isArray(local));
test.ok(!clone.__isRegExp(alien));
test.ok(!clone.__isRegExp(local));
test.done();
});
};
exports["recognize RegExp object"] = function (test) {
var results = apartContext(null, "results = /foo/", function(alien) {
var local = /bar/;
test.ok(clone.__isRegExp(alien)); // recognize in other context.
test.ok(clone.__isRegExp(local)); // recognize in local context.
test.ok(!clone.__isArray(alien));
test.ok(!clone.__isArray(local));
test.ok(!clone.__isDate(alien));
test.ok(!clone.__isDate(local));
test.done();
});
};
Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
History of cookies.txt
=====
### 0.1.2
* Fix: Parse 2 cookies files, the result is merged into one globale object. Reset cookie object when call parse() method.
### 0.1.1
* parse cookies only
* remove old jar request support; new way: ``` request.get({url:'url', jar:true, headers:{Cookie:cookie.getCookieString('url')}});```
* return http request header "Cookie" string by request.url.
### 0.1.0
* basic wget cookies.txt format file parser.
* working with module request: _NOT work with request:jar Object of new version request_.
cookies.txt
===========
TestStatus:[![Test Status](https://travis-ci.org/mxfli/node-cookies.txt.png)](https://travis-ci.org/mxfli/node-cookies.txt)
#README
This is a _wget cookies.txt_ formart parser for nodejs.
Convert wget cookies.txt format file into JSON boject.
Working whith `http.requst` or `request module`.
##Install
```npm install cookies.txt```
##Usage
```
var cookie = require('cookies.txt');
cookie.parse('your cookies.txt file path here.', function(jsonCookieObj){
//your codes here
//...
});
```
### Working with request module
```
var request = require('request');
var cookie = requeire('cookies.txt');
cookie.parse('your cookies.txt file path here.', function(jsonCookieObj){
//your codes here
request.get({
url:'the http url',
jar:true,
encoding:null,
headers:{
Cookie:cookie.getCookieString('the url')}})
.pipe(AWritebleStreamInstance);
//...
});
```
##License
MIT
"use strict";
//This is a wget cookies.txt parser for nodejs
//Author:@mxfli
//date::2011年 12月 13日 星期二 13:33:06 UTC
var fs = require('fs');
var url = require('url');
var assert = require('assert');
var COOKIE_FIELDS = ['domain', 'httponly', 'path', 'secure', 'expires', 'name', 'value'];
//Object contains parsed cookies from cookies.txt
var COOKIES = [];
/**
* Parse cookies file and return the result to cb;
*/
var parse = function (file, cb) {
assert(fs.existsSync(file));
assert(typeof cb === 'function');
//Fix: 2 cookies file is merged in on Object.
COOKIES.length = 0;
fs.readFile(file, function read(err, buffer) {
if (err) {
throw err;
}
//change dos/mac files to unix format
var toUnix = function (str) {
assert(typeof str === 'string');
return str.replace(/\\r\\n/g, '\r').replace(/\\r/g, '\n');
};
var str = toUnix(buffer.toString('utf8'));
//console.log('Cookies.txt content: \n', str);
var cookies = str.split('\n');
//console.log(cookies.length);
cookies.forEach(function (line) {
//console.log(index,':',line);
line = line.trim();
if (line.length > 0 && !/^#/.test(line)) {
var cookie = {};
line.split(/\s/).forEach(function (c, index) {
if (COOKIE_FIELDS[index] === 'expires') {
c = (new Date(parseInt(c, 10) * 1000));
}
cookie[COOKIE_FIELDS[index]] = c;
});
COOKIES.push(cookie);
}
});
console.log("node-Cookies.txt load:", COOKIES.length, 'cookies.');
cb(COOKIES);
});
};
exports.parse = parse;
exports.getCookieString = function (urlStr) {
var urlObj = url.parse(urlStr, false);
var result = COOKIES.reduce(function (pre, cookie) {
if (urlObj.hostname === cookie.domain && urlObj.pathname.indexOf(cookie.path) === 0) {
pre.push(cookie.name + '=' + cookie.value);
}
return pre;
}, []).join(';');
console.log('Get "Cookie" :', result);
return result;
};
{
"name": "cookies.txt",
"description": "This is a wget cookies.txt formart parser for nodejs and request.",
"tags": [
"wget",
"cookie",
"cookies.txt",
"http",
"request"
],
"scripts": {
"test": "node test/test.js"
},
"version": "0.1.2",
"author": "Inaction <Inaction.me@gmail.com> (http://inaction.me)",
"repository": {
"type": "git",
"url": "git://github.com/mxfli/node-cookies.txt.git"
},
"bugs": {
"url": "https://github.com/mxfli/node-cookies.txt/issues"
},
"engines": {
"node": ">= 0.4.1"
},
"main": "index.js",
"dependencies": {},
"devDependencies": {},
"_from": "cookies.txt@0.1.2",
"_resolved": "http://registry.npm.taobao.org/cookies.txt/download/cookies.txt-0.1.2.tgz"
}
\ No newline at end of file
Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
before_install:
- '[ "${TRAVIS_NODE_VERSION}" != "0.8" ] || npm install -g npm@1.4.28'
- npm install -g npm@latest
0.0.4 / 2015-06-29
==================
* package: update "mocha" to v2
* package: add RFC to the "keywords" section
* travis: test node v0.8, v0.10, and v0.12
* README: use SVG for Travis-CI badge
* test: more tests
0.0.3 / 2014-01-08
==================
* index: fix a URI with a comma in the data portion
0.0.2 / 2014-01-08
==================
* index: use unescape() instead of decodeURIComponent()
* test: add more tests from Mozilla
0.0.1 / 2014-01-02
==================
* add `README.md`
* index: default the `charset` property to "US-ASCII"
* default encoding is "ascii"
* default `type` to "text/plain" when none is given
* initial commit
data-uri-to-buffer
==================
### Generate a Buffer instance from a [Data URI][rfc] string
[![Build Status](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer.svg?branch=master)](https://travis-ci.org/TooTallNate/node-data-uri-to-buffer)
This module accepts a ["data" URI][rfc] String of data, and returns a
node.js `Buffer` instance with the decoded data.
Installation
------------
Install with `npm`:
``` bash
$ npm install data-uri-to-buffer
```
Example
-------
``` js
var dataUriToBuffer = require('data-uri-to-buffer');
// plain-text data is supported
var uri = 'data:,Hello%2C%20World!';
var decoded = dataUriToBuffer(uri);
console.log(decoded.toString());
// 'Hello, World!'
// base64-encoded data is supported
uri = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D';
decoded = dataUriToBuffer(uri);
console.log(decoded.toString());
// 'Hello, World!'
```
API
---
### dataUriToBuffer(String uri) → Buffer
The `type` property on the Buffer instance gets set to the Content-Type portion of
the "mediatype" portion of the "data" URI, or defaults to `"text/plain"` if not
specified.
The `charset` property on the Buffer instance gets set to the Charset portion of
the "mediatype" portion of the "data" URI, or defaults to `"US-ASCII"` if not
specified.
License
-------
(The MIT License)
Copyright (c) 2014 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
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.
[rfc]: http://tools.ietf.org/html/rfc2397
/**
* Module exports.
*/
module.exports = dataUriToBuffer;
/**
* Returns a `Buffer` instance from the given data URI `uri`.
*
* @param {String} uri Data URI to turn into a Buffer instance
* @return {Buffer} Buffer instance from Data URI
* @api public
*/
function dataUriToBuffer (uri) {
if (!/^data\:/i.test(uri)) {
throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
}
// strip newlines
uri = uri.replace(/\r?\n/g, '');
// split the URI up into the "metadata" and the "data" portions
var firstComma = uri.indexOf(',');
if (-1 === firstComma || firstComma <= 4) throw new TypeError('malformed data: URI');
// remove the "data:" scheme and parse the metadata
var meta = uri.substring(5, firstComma).split(';');
var base64 = false;
var charset = 'US-ASCII';
for (var i = 0; i < meta.length; i++) {
if ('base64' == meta[i]) {
base64 = true;
} else if (0 == meta[i].indexOf('charset=')) {
charset = meta[i].substring(8);
}
}
// get the encoded data portion and decode URI-encoded chars
var data = unescape(uri.substring(firstComma + 1));
var encoding = base64 ? 'base64' : 'ascii';
var buffer = new Buffer(data, encoding);
// set `.type` property to MIME type
buffer.type = meta[0] || 'text/plain';
// set the `.charset` property
buffer.charset = charset;
return buffer;
}
{
"name": "data-uri-to-buffer",
"version": "0.0.4",
"description": "Generate a Buffer instance from a Data URI string",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "mocha --reporter spec"
},
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-data-uri-to-buffer.git"
},
"keywords": [
"data",
"uri",
"datauri",
"data-uri",
"buffer",
"convert",
"rfc2397",
"2397"
],
"author": "Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/TooTallNate/node-data-uri-to-buffer/issues"
},
"homepage": "https://github.com/TooTallNate/node-data-uri-to-buffer",
"devDependencies": {
"mocha": "2"
},
"_from": "data-uri-to-buffer@0.0.4",
"_resolved": "http://registry.npm.taobao.org/data-uri-to-buffer/download/data-uri-to-buffer-0.0.4.tgz"
}
\ No newline at end of file
/**
* Module dependencies.
*/
var assert = require('assert');
var dataUriToBuffer = require('../');
describe('data-uri-to-buffer', function () {
it('should decode bare-bones Data URIs', function () {
var uri = 'data:,Hello%2C%20World!';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('Hello, World!', buf.toString());
});
it('should decode bare-bones "base64" Data URIs', function () {
var uri = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('Hello, World!', buf.toString());
});
it('should decode plain-text Data URIs', function () {
var html = '<!DOCTYPE html>'+
'<html lang="en">'+
'<head><title>Embedded Window</title></head>'+
'<body><h1>42</h1></body>'+
'</html>';
// Escape the HTML for URL formatting
var uri = 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
var buf = dataUriToBuffer(uri);
assert.equal('text/html', buf.type);
assert.equal('utf-8', buf.charset);
assert.equal(html, buf.toString());
});
// the next 4 tests are from:
// https://bug161965.bugzilla.mozilla.org/attachment.cgi?id=94670&action=view
it('should decode "ISO-8859-8 in Base64" URIs', function () {
var uri = 'data:text/plain;charset=iso-8859-8-i;base64,+ezl7Q==';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('iso-8859-8-i', buf.charset);
assert.equal(4, buf.length);
assert.equal(0xf9, buf[0]);
assert.equal(0xec, buf[1]);
assert.equal(0xe5, buf[2]);
assert.equal(0xed, buf[3]);
});
it('should decode "ISO-8859-8 in URL-encoding" URIs', function () {
var uri = 'data:text/plain;charset=iso-8859-8-i,%f9%ec%e5%ed';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('iso-8859-8-i', buf.charset);
assert.equal(4, buf.length);
assert.equal(0xf9, buf[0]);
assert.equal(0xec, buf[1]);
assert.equal(0xe5, buf[2]);
assert.equal(0xed, buf[3]);
});
it('should decode "UTF-8 in Base64" URIs', function () {
var uri = 'data:text/plain;charset=UTF-8;base64,16nXnNeV150=';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('UTF-8', buf.charset);
assert.equal(8, buf.length);
assert.equal('שלום', buf.toString('utf8'));
});
it('should decode "UTF-8 in URL-encoding" URIs', function () {
var uri = 'data:text/plain;charset=UTF-8,%d7%a9%d7%9c%d7%95%d7%9d';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('UTF-8', buf.charset);
assert.equal(8, buf.length);
assert.equal('שלום', buf.toString('utf8'));
});
// this next one is from Wikipedia IIRC
it('should decode "base64" Data URIs with newlines', function () {
var uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA\n' +
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO\n' +
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
var buf = dataUriToBuffer(uri);
assert.equal('image/png', buf.type);
assert.equal('iVBORw0KGgoAAAANSUhEUgAAAAUA' +
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +
'9TXL0Y4OHwAAAABJRU5ErkJggg==', buf.toString('base64'));
});
it('should decode a plain-text URI with a space character in it', function () {
var uri = 'data:,foo bar';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('foo bar', buf.toString());
});
it('should decode data with a "," comma char', function () {
var uri = 'data:,a,b';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal('a,b', buf.toString());
});
it('should decode data with traditionally reserved characters like ";"', function () {
var uri = 'data:,;test';
var buf = dataUriToBuffer(uri);
assert.equal('text/plain', buf.type);
assert.equal(';test', buf.toString());
});
});
Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2015 Elijah Insua
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.
# defaults
A simple one level options merge utility
## install
`npm install defaults`
## use
```javascript
var defaults = require('defaults');
var handle = function(options, fn) {
options = defaults(options, {
timeout: 100
});
setTimeout(function() {
fn(options);
}, options.timeout);
}
handle({ timeout: 1000 }, function() {
// we're here 1000 ms later
});
handle({ timeout: 10000 }, function() {
// we're here 10s later
});
```
## summary
this module exports a function that takes 2 arguments: `options` and `defaults`. When called, it overrides all of `undefined` properties in `options` with the clones of properties defined in `defaults`
Sidecases: if called with a falsy `options` value, options will be initialized to a new object before being merged onto.
## license
[MIT](LICENSE)
var clone = require('clone');
module.exports = function(options, defaults) {
options = options || {};
Object.keys(defaults).forEach(function(key) {
if (typeof options[key] === 'undefined') {
options[key] = clone(defaults[key]);
}
});
return options;
};
\ No newline at end of file
../../_clone@1.0.2@clone
\ No newline at end of file
{
"name": "defaults",
"version": "1.0.3",
"description": "merge single level defaults over a config object",
"main": "index.js",
"scripts": {
"test": "node test.js"
},
"repository": {
"type": "git",
"url": "git://github.com/tmpvar/defaults.git"
},
"keywords": [
"config",
"defaults"
],
"author": "Elijah Insua <tmpvar@gmail.com>",
"license": "MIT",
"readmeFilename": "README.md",
"dependencies": {
"clone": "^1.0.2"
},
"devDependencies": {
"tap": "^2.0.0"
},
"_from": "defaults@1.0.3",
"_resolved": "http://registry.npm.taobao.org/defaults/download/defaults-1.0.3.tgz"
}
\ No newline at end of file
var defaults = require('./'),
test = require('tap').test;
test("ensure options is an object", function(t) {
var options = defaults(false, { a : true });
t.ok(options.a);
t.end()
});
test("ensure defaults override keys", function(t) {
var result = defaults({}, { a: false, b: true });
t.ok(result.b, 'b merges over undefined');
t.equal(result.a, false, 'a merges over undefined');
t.end();
});
test("ensure defined keys are not overwritten", function(t) {
var result = defaults({ b: false }, { a: false, b: true });
t.equal(result.b, false, 'b not merged');
t.equal(result.a, false, 'a merges over undefined');
t.end();
});
test("ensure defaults clone nested objects", function(t) {
var d = { a: [1,2,3], b: { hello : 'world' } };
var result = defaults({}, d);
t.equal(result.a.length, 3, 'objects should be clones');
t.ok(result.a !== d.a, 'objects should be clones');
t.equal(Object.keys(result.b).length, 1, 'objects should be clones');
t.ok(result.b !== d.b, 'objects should be clones');
t.end();
});
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
[*.js]
indent_style = tab
[{package.json,.travis.yml,*.md}]
indent_style = space
indent_size = 2
fail_on_violations: true
jshint:
config_file: .jshintrc
{
"preset": "google",
"fileExtensions": [ ".js" ],
"validateIndentation": "\t",
"jsDoc": {
"disallowNewlineAfterDescription": true
},
"disallowMultipleLineBreaks": null,
disallowSpacesInsideObjectBrackets: null,
"requireDotNotation": null,
"maximumLineLength": 80,
"requireCapitalizedConstructors": true,
"disallowEmptyBlocks": true,
"excludeFiles": [ "node_modules/**", "coverage/**", "dist/**" ]
}
{
"node": true,
"browser": true,
"mocha": true,
"globals" : {
"prompt": false,
"alert": false,
"jQuery": false,
"$": false,
"Promise": true,
"__horseman": true,
"___obj": true
},
"sub": true,
"boss": true,
"quotmark": "single",
"evil": true,
"maxlen": 80,
"validthis": true,
"strict": true
}
John Titus <john.titus@gmail.com> <john.titus@gmail.com>
John Titus <john.titus@gmail.com> <john.titus@trustedconcepts.com>
node_modules
test/*.png
test.js
\ No newline at end of file
Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
language: node_js
node_js:
- '0.10'
- '0.12'
- '4'
- '5'
- '6'
- '7'
sudo: false
before_install:
sh -c 'npm install phantomjs-prebuilt@$PHANTOMJS || npm install phantomjs@$PHANTOMJS'
env:
- PHANTOMJS=1
- PHANTOMJS=2
John Titus <john.titus@gmail.com>
Alex Layton <alex@layton.in> (http://alex.layton.in)
# Change Log
All notable changes to this project will be documented in this file.
## 3.3.0 - 2017-04-06
### Added
- `phantomOptions` option for passing arbitrary PhantomJS CLI options -
thanks @fabiocorneti
- Support for per-action timeouts on `.waitFor` type actions - thanks @piercus
### Fixed
- `.boundingRectangle()` sometimes not using jQuery when it could -
thanks @robsgreen
- `.evaluate()` sometimes failing due to an utilized internal variable -
thanks @robertpallas
### Changed
- Removed `clientScripts` option (it had no effect anyways)
## 3.2.0 - 2016-10-21
### Added
- `diskCache` and `diskCachePath` options - thanks @efernandesng
## 3.1.1 - 2016-06-17
Republish 3.1.0 without unwanted files which broke Windows installation
## 3.1.0 - 2016-06-15
### Added
- .plainText() action - thanks @mzhangARS
### Changed
- Removed `port` constructor option (it no longer had any effect)
## 3.0.1 - 2016-04-12
### Fixed
- .injectJs() now properly rejects when it fails
- #158 - bug with `injectBluebird` option
## 3.0.0 - 2016-04-06
### Added
- Support for adding custom actions via `Horseman.registerAction`
## 3.0.0-beta2 - 2016-04-05
### Added
- .closeTab() action removes a tab and closes its page
- tabClosed event fired when a tab is closed
(by .closeTab() or something else)
- .frameName() action
- .frameCount() action
- .frameNames() action
- .switchToFocusedFrame() action
- .switchToFrame() action
- .switchToMainFrame() action
- .switchToParentFrame() action
- .download() action allows getting the raw contents of a URL
(even works for binary files is using PhantomJS 2 or newer)
### Changed
- .log() now preserves resolution value of previous action
- More output added to verbose debugging
### Fixed
- More readable stack traces from .evaluate() rejections
(especially with long stack traces on)
- Occasional bug with returning undefined in .evaluate() function
### Deprecated
- .switchToChildFrame() action is deprecated
since PhantomJS deprecated it
## 3.0.0-beta1 - 2016-03-22
### Added
- bluebird 3 functions are now chainable with Horseman actions
- Support for callback/Promises in .evaluate() functions
- .at() action allows registering callbacks to run in PhantomJS JavaScript
environment (see Reame for details)
- .setProxy() action allows changing Phantom's proxy settings
(requires PhantomJS 2.0.0 or newer)
- .includeJs() action allows injecting JavaScript from a URL
- .put() action
- Support for SlimerJS as well as PhantomJS - thanks @w33ble
- Support for PhantomJS remote debugger - thanks @dustinblackman
- Support for reading cookies.txt files
- Options for injecting bluebird into each page for using Promises in browser
- Option for automatically switching to newly opened tabs
- Option for more verbose debug
### Changed
- Horseman Promises now reject on error
- Waiting actions now reject on timeout (timeout callback is still called too)
- Phantom's reourceTimeout now set to match Horseman's timeout
- Horseman will use Phantom from the phantomjs-prebuilt/phantomjs npm packages
if installed (still overridden by phantomPath option)
### Fixed
- .open() now rejects on fail - thanks @w33ble.
- .crop() now works with zoomFactor other than 1 - thanks @wong2.
- .waitForSelector() now uses JQuery for selectors (when avialable)
- navigationRequested callback now called with correct parameters -
thanks @grahamkennery.
- Tabs/pages not opened by Horseman (e.g. by a link)
are now correctly added to Horseman's list of tabs
### Updated
- bluebird dependency to 3.0.1
- node-phantom-simple dependency to 2.2.4
- clone dependency to 1.0.2
## 2.8.2 - 2015-11-23
### Fixed
- #74 - do not try to exit PhantomJS when it failed to initialize
## 2.8.1 - 2015-11-06
### Fixed
- .upload() now works in PhantomJS 1.x line (still broken in 2.x line) -
thanks @flashhhh
- logging for falsy arguments - thanks @awlayton
## 2.8.0 - 2015-10-28
### Added
- .cropBase64(). Thanks @jeprojects!
### Updated
- node-phantom-simple dependency to version 2.1.0.
- Updated readme with examples on how to set header/footer contents.
## 2.7.1 - 2015-10-21
### Fixed
- If an exception was thrown, close() wouldn't get called. Merged #58.
Thanks @awlayton!
## 2.7.0 - 2015-10-15
### Updated
- Makes promise functions (like then, catch, tap) chainable with the rest of
Horseman actions. Merges #57. Thanks @awlayton!
## 2.6.0 - 2015-10-08
### Updated
- .close() is now chainable. Updated readme with examples.
## 2.5.0 - 2015-10-08
### Added
- .log(). Closes #54.
### Fixed
- .viewport() wasn't returning the actual viewport size.
## 2.4.0 - 2015-10-08
### Added
- .do(). Closes #53.
## 2.3.0 - 2015-10-01
### Added
- Support for multiple tabs. Closes #49.
- .status(). Returns the HTTP status code from the last opened page.
## 2.2.1 - 2015-10-01
### Fixed
- `.waitFor` bug fix. Closes #45.
## 2.2.0 - 2015-09-29
### Added
- `.crop()`. Closes #51.
## 2.1.0 - 2015-09-27
### Added
- API is chainable again, thanks to @awlayton. Addresses #46.
## 2.0.2 - 2015-09-21
### Fixed
- `waitForNextPage` was broken. Fixes #44 (thanks @edge)
## 2.0.1 - 2015-09-14
### Upgraded
- Moved to `node-phantom-simple` 2.0.4.
## 2.0.0 - 2015-09-10
### Changed
- Complete API rewrite to use Promises.
- Removed dependency on `deasync`.
- Tab support removed, will add back in the future.
## 1.5.6 - 2015-08-17
### Fixed
- #39. Upgraded to node-phantom-simple 2.0.3.
## 1.5.5 - 2015-08-12
### Changed
- Upgraded to node-phantom-simple 2.0.2. Close #37.
- Upgraded to Mocha 2.2.5 to remove "child_process: customFds option is
deprecated, use stdio instead" message when testing.
- Edited this document to reflect actual release dates from 1.4.1 - present.
## 1.5.4 - 2015-07-22
### Fixed
- Merges #36 - Setting via horseman.value( newVal ) now fires a change event.
Thanks @fpinzn.
## 1.5.3 - 2015-07-13
### Fixed
- Fix #27 & 33 - .cookies() wasn't returning a list of cookies for the current
page. Now fixed.
## 1.5.2 - 2015-07-01
### Fixed
- Fix #30 - crop() now chainable. Thanks @jackstrain.
## 1.5.1 - 2015-03-10
### Fixed
- Readme issue
## 1.5.0 - 2015-03-10
### Added
- switchToChildFrame() (issue #18, thanks @easyrider)
## 1.4.1 - 2015-03-04
### Fixed
- Readme issue
## 1.4.0 - 2015-03-04
### Added
- keyboardEvent function
- mouseEvent function
- exposed `phantomPath` instantiation option
## 1.3.6 - 2015-03-03
### Added
- status function.
- post function.
## 1.3.5 - 2015-03-02
### Fixed
- Updated documentation to address issues #12 and #14.
## 1.3.4 - 2015-02-27
### Fixed
- Forgot to merge cookiesFile branch :(
## 1.3.3 - 2015-02-27
### Added
- Exposes `cookiesFile` option. (Issue #8).
## 1.3.2 - 2015-02-27
### Fixed
- Removed `weak` option from Readme.md (issue #10).
- Fixed horseman.close() bug. (issue #11)
## 1.3.1 - 2015-02-27
### Fixed
- Copyright years in LICENSE (thanks @fay-jai)
- .waitForSelector() text in Readme.me (issue #7. thanks @bchr02)
## 1.3.0 - 2015-02-26
### Added
- tabCount function.
- switchToTab function.
- openTab function.
- tabCreated event.
## 1.2.2 - 2015-02-26
### Fixed
- Phantom options, like `loadImages` were not being honored in 1.2.1.
## 1.2.1 - 2015-02-26
### Changed
- Swapped out `phantom` for `node-phantom-simple` to fix some performance
issues (see issue #6). This a major change internally,
but does not change the API and all tests are passing.
## 1.2.0 - 2015-02-24
### Added
- zoom function.
- pdf function.
- scrollTo function.
- headers function.
## 1.1.0 - 2015-02-24
### Added
- screenshotBase64 function.
- CHANGELOG.md
## 1.0.0 - 2015-02-12
The MIT License (MIT)
Copyright (c) 2014-2015 John Titus
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.
// Find the number of follower for each account. Spawns a new horseman for each user for faster results.
var Horseman = require('node-horseman');
var users = ['PhantomJS',
'ariyahidayat',
'detronizator',
'KDABQt',
'lfranchi',
'jonleighton',
'_jamesmgreene',
'Vitalliumm'];
users.forEach( function( user ){
var horseman = new Horseman();
horseman
.open('http://mobile.twitter.com/' + user)
.text('.UserProfileHeader-stat--followers .UserProfileHeader-statCount')
.then(function(text){
console.log( user + ': ' + text );
})
.finally(function(){
return horseman.close();
});
});
// Grab links from Google.
var Horseman = require("node-horseman");
var horseman = new Horseman();
var links = [];
function getLinks(){
return horseman.evaluate( function(){
// This code is executed in the browser.
var links = [];
$("div.g h3.r a").each(function( item ){
var link = {
title : $(this).text(),
url : $(this).attr("href")
};
links.push(link);
});
return links;
});
}
function hasNextPage(){
return horseman.exists("#pnnext");
}
function scrape(){
return new Promise( function( resolve, reject ){
return getLinks()
.then(function(newLinks){
links = links.concat(newLinks);
if ( links.length < 30 ){
return hasNextPage()
.then(function(hasNext){
if (hasNext){
return horseman
.click("#pnnext")
.wait(1000)
.then( scrape );
}
});
}
})
.then( resolve );
});
}
horseman
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0")
.open("http://www.google.com")
.type("input[name='q']","horseman")
.click("input[value='Google Search']")
.keyboardEvent("keypress",16777221)
.waitForSelector("div.g")
.then( scrape )
.finally(function(){
console.log(links.length)
horseman.close();
});
// Find pizza in Mountain View using Yelp
var Horseman = require("node-horseman");
var horseman = new Horseman();
horseman
.open('http://lite.yelp.com/search?find_desc=pizza&find_loc=94040&find_submit=Search')
.text('address')
.log()
.close();
\ No newline at end of file
'use strict';
// Extend our copy of bluebird
module.exports = require('bluebird/js/release/promise')();
../../_bluebird@3.5.0@bluebird
\ No newline at end of file
../../_clone@1.0.2@clone
\ No newline at end of file
../../_cookies.txt@0.1.2@cookies.txt
\ No newline at end of file
../../_data-uri-to-buffer@0.0.4@data-uri-to-buffer
\ No newline at end of file
../../_debug@2.6.8@debug
\ No newline at end of file
../../_defaults@1.0.3@defaults
\ No newline at end of file
../../_node-phantom-simple@2.2.4@node-phantom-simple
\ No newline at end of file
{
"name": "node-horseman",
"version": "3.3.0",
"description": "Run PhantomJS from Node",
"repository": {
"type": "git",
"url": "https://github.com/johntitus/node-horseman.git"
},
"main": "lib/index",
"directories": {
"test": "test"
},
"dependencies": {
"bluebird": "^3.0.1",
"clone": "^1.0.2",
"cookies.txt": "^0.1.1",
"data-uri-to-buffer": "0.0.4",
"debug": "^2.1.1",
"defaults": "~1.0.0",
"node-phantom-simple": "^2.2.4"
},
"devDependencies": {
"express": "^4.10.4",
"hoxy": "^3.2.0",
"mocha": "^2.2.5",
"mocha.parallel": "^0.12.0",
"request": "^2.69.0",
"rmdir": "^1.2.0",
"semver": "^5.1.0",
"should": "^8.2.2"
},
"scripts": {
"lint": "jshint .",
"test": "mocha -R spec"
},
"keywords": [
"phantomjs",
"horseman",
"headless",
"browser"
],
"author": "John Titus <john.titus@gmail.com>",
"license": "MIT",
"_from": "node-horseman@3.3.0",
"_resolved": "http://registry.npm.taobao.org/node-horseman/download/node-horseman-3.3.0.tgz"
}
\ No newline at end of file
body, html {
background-color: white;
}
a {
margin-bottom: 3px;
}
\ No newline at end of file
# Dummy cookies.txt for horseman tests
.httpbin.org TRUE / FALSE 99999999 test cookie
.httpbin.org TRUE / FALSE 99999999 test2 cookie2
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Horseman frame 1</title>
</head>
<body id="f1">
<h1>This is frame 1.</h1>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Horseman frame 2</title>
</head>
<frameset cols="50%,50%%">
<frame src="frame3.html" name="frame31">
<frame src="frame3.html" name="frame32">
</frameset>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Horseman frame 3</title>
</head>
<body id="f3">
<h1>This is frame 3.</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Horseman test frames</title>
</head>
<frameset cols="50%,50%%">
<frame src="frame1.html" name="frame1">
<frame src="frame2.html" name="frame2">
</frameset>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<link rel="stylesheet" type="text/css" href="/base.css">
</head>
<body>
<p id="text">
This is my code.
</p>
<input type="text" name="input1">
<select id="select1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="file" id="upload">
<a id="link" href="next.html">Next Page</a>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Horseman fake jQuery page</title>
<script>
window.jQuery = window.$ = {
fn: {
jquery: 'Not really jQuery'
}
};
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Horseman new tab</title>
</head>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Next Page</title>
<link rel="stylesheet" type="text/css" href="/base.css">
</head>
<body>
<a href="/">Root</a>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Horseman test link open new tab</title>
</head>
<a href="./newtab.html" target="new-tab" id="newtab">Open new tab</a>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Plain Page</title>
</head>
<body>
<p>This is some plain text.</p>
<input type="text" placeholder="This is not text." />
</body>
</html>
\ No newline at end of file
body, html {
background-color: #FF0000;
}
\ No newline at end of file
Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
2.2.4 / 2016-01-26
------------------
- Fix: parse 127.0.0.0/8 properly, #115, thanks to @janl.
2.2.3 / 2016-01-17
------------------
- Allow engine options to be an array to pass in verbatim keys and values.
2.2.2 / 2015-12-30
------------------
- One more improvement of phantom exit check, #102, thanks to @siboulet.
2.2.1 / 2015-12-09
------------------
- Improved phantom die detection (connection loss), #100, thanks to @joscha.
2.2.0 / 2015-11-28
------------------
- Don't write messages to console - use `debug` instead, #96.
2.1.1 / 2015-11-07
------------------
- Improved port detection support for DO droplets, #76, thanks to @svvac.
2.1.0 / 2015-10-28
------------------
- Replaced SIGINT/SIGTERM handlers with watchdog, #81.
- Improved nested page props support, #90.
- Added support for `page.header.contents` & `page.footer.contents`, #78.
2.0.6 / 2015-10-09
------------------
- Added `.setProxy()` support.
2.0.5 / 2015-09-17
------------------
- Removed uncaught exception handler and forced exit (that should be in parent
application)
- Added process events proxy to avoid memleak warnings on parallel browser
instances run.
- Added `onConfirm` details to known issues.
2.0.4 / 2015-08-22
------------------
- Fixed poll loop termination after browser die (missed in 2.0.3).
2.0.3 / 2015-08-17
------------------
- Fixed poll loop termination after `.close()`.
2.0.2 / 2015-08-02
------------------
- Added `clearMemoryCache()` engine method support.
- Coding style update.
- Added linter to tests.
2.0.1 / 2015-07-12
------------------
- Improved iproute2 support (different output format in Ubuntu 15.04+).
2.0.0 / 2015-07-09
------------------
- Added SlimerJS support.
- Moved callbacks to last position in all functions.
- old style calls still work but show deprecation message.
- Renamed `options.phantomPath` -> `options.path`
- old style options still work but show deprecation message.
- Added FreeBSD support.
- Improved Linux support - try iproute2 before net-tools.
- Added dot notation support for nested properties in `.set` / `.get`.
- Defined missed `onResourceTimeout` handler.
- Defined `onAuthPrompt` handler, specific to SlimerJS.
- Fixed Win32 support.
- Fixed Yosemite support with multiname localhost aliases.
- Return proper errors when PhantomJS / SlimerJS process dies.
- Fixed `waitForSelector` callback result.
- Fixed possible result corruption in `evaluate`.
- Rewritten tests & automated testing.
1.2.0 / 2014-03-19
------------------
- Tests rewrite & code cleanup.
1.1.1 / 2014-03-12
------------------
- Fix possible ECONNRESET after exit.
1.1.0 / 2014-02-10
------------------
- Fix and work-around broken includeJs function.
Previous versions
-----------------
...
Copyright (c) 2013-2015 Matt Sergeant
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.
node-phantom-simple
===================
[![Build Status](https://img.shields.io/travis/baudehlo/node-phantom-simple/master.svg?style=flat)](https://travis-ci.org/baudehlo/node-phantom-simple)
[![NPM version](https://img.shields.io/npm/v/node-phantom-simple.svg?style=flat)](https://www.npmjs.org/package/node-phantom-simple)
> A bridge between [PhantomJS](http://phantomjs.org/) / [SlimerJS](https://slimerjs.org/)
and [Node.js](http://nodejs.org/).
This module is API-compatible with
[node-phantom](https://www.npmjs.com/package/node-phantom) but doesn't rely on
`WebSockets` / `socket.io`. In essence the communication between Node and
Phantom / Slimer has been simplified significantly. It has the following advantages
over `node-phantom`:
- Fewer dependencies/layers.
- Doesn't use the unreliable and huge socket.io.
- Works under [`cluster`](http://nodejs.org/api/cluster.html) (node-phantom
does not, due to [how it works](https://nodejs.org/api/cluster.html#cluster_how_it_works))
`server.listen(0)` works in cluster.
- Supports SlimerJS.
Migrating 1.x -> 2.x
--------------------
Your software should work without changes, but can show deprecation warning
about outdated signatures. You need to update:
- `options.phantomPath` -> `options.path`
- in `.create()` `.evaluate()` & `.waitForSelector()` -> move `callback` to last
position of arguments list.
That's all!
Installing
----------
```bash
npm install node-phantom-simple
# Also need phantomjs OR slimerjs:
npm install phantomjs
# OR
npm install slimerjs
```
__Note__. SlimerJS is not headless and requires a windowing environment.
Under Linux/FreeBSD/OSX [xvfb can be used to run headlessly.](https://docs.slimerjs.org/current/installation.html#having-a-headless-slimerjs). For example, if you wish
to run SlimerJS on Travis-CI, add those lines to your `.travis.yml` config:
```yaml
before_script:
- export DISPLAY=:99.0
- "sh -e /etc/init.d/xvfb start"
```
Usage
-----
You can use it exactly like node-phantom, and the entire API of PhantomJS
should work, with the exception that every method call takes a callback (always
as the last parameter), instead of returning values.
For example, this is an adaptation of a
[web scraping example](http://net.tutsplus.com/tutorials/javascript-ajax/web-scraping-with-node-js/):
```js
var driver = require('node-phantom-simple');
driver.create({ path: require('phantomjs').path }, function (err, browser) {
return browser.createPage(function (err, page) {
return page.open("http://tilomitra.com/repository/screenscrape/ajax.html", function (err,status) {
console.log("opened site? ", status);
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function (err) {
// jQuery Loaded.
// Wait for a bit for AJAX content to load on the page. Here, we are waiting 5 seconds.
setTimeout(function () {
return page.evaluate(function () {
//Get what you want from the page using jQuery. A good way is to populate an object with all the jQuery commands that you need and then return the object.
var h2Arr = [],
pArr = [];
$('h2').each(function () { h2Arr.push($(this).html()); });
$('p').each(function () { pArr.push($(this).html()); });
return {
h2: h2Arr,
p: pArr
};
}, function (err,result) {
console.log(result);
browser.exit();
});
}, 5000);
});
});
});
});
```
### .create(options, callback)
__options__ (not mandatory):
- __path__ (String) - path to phantomjs/slimerjs, if not set - will search in $PATH
- __parameters__ (Array) - CLI params for executed engine, [ { nave: value } ].
You can also pass in an array to use verbatim names and values.
- __ignoreErrorPattern__ (RegExp) - a regular expression that can be used to
silence spurious warnings in console, generated by Qt and PhantomJS.
On Mavericks, you can use `/CoreText/` to suppress some common annoying
font-related warnings.
For example
```js
driver.create({ parameters: { 'ignore-ssl-errors': 'yes' } }, callback)
driver.create({ parameters: ['-jsconsole', '-P', 'myVal']} }, callback)
```
will start phantom as:
```bash
phantomjs --ignore-ssl-errors=yes
```
You can rely on globally installed engines, but we recommend to pass path explicit:
```js
driver.create({ path: require('phantomjs').path }, callback)
// or for slimer
driver.create({ path: require('slimerjs').path }, callback)
```
You can also have a look at [the test directory](tests/) to see some examples
of using the API, however the de-facto reference is the
[PhantomJS documentation](https://github.com/ariya/phantomjs/wiki/API-Reference).
Just mentally substitute all return values for callbacks.
WebPage Callbacks
-----------------
All of the `WebPage` callbacks have been implemented including `onCallback`,
and are set the same way as with the core phantomjs library:
```js
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
```
This includes the `onPageCreated` callback which receives a new `page` object.
Properties
----------
Properties on the [WebPage](https://github.com/ariya/phantomjs/wiki/API-Reference-WebPage)
and [Phantom](https://github.com/ariya/phantomjs/wiki/API-Reference-phantom)
objects are accessed via the `get()`/`set()` method calls:
```js
page.get('content', function (err, html) {
console.log("Page HTML is: " + html);
});
page.set('zoomfactor', 0.25, function () {
page.render('capture.png');
});
// You can get/set nested values easy!
page.set('settings.userAgent', 'PhAnToSlImEr', callback);
```
Known issues
------------
Engines are buggy. Here are some cases you should know.
- `.evaluate` can return corrupted result:
- SlimerJS: undefined -> null.
- PhantomJS:
- undefined -> null
- null -> '' (empty string)
- [ 1, undefined, 2 ] -> null
- `page.onConfirm()` handler can not return value due async driver nature.
Use `.setFn()` instead: `page.setFn('onConfirm', function () { return true; })`.
License
-------
[MIT](https://github.com/baudehlo/node-phantom-simple/blob/master/LICENSE)
Other
-----
Made by Matt Sergeant for Hubdoc Inc.
/*global phantom*/
/*eslint-disable strict*/
var webpage = require('webpage');
var webserver = require('webserver').create();
var system = require('system');
var pages = {};
var page_id = 1;
var callback_stack = [];
// Max interval without requests from master process
var WATCHDOG_TIMEOUT = 30000;
phantom.onError = function (msg, trace) {
var msgStack = [ 'PHANTOM ERROR: ' + msg ];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
});
}
system.stderr.writeLine(msgStack.join('\n'));
phantom.exit(1);
};
var watchdog_timer_id = null;
// Kill phantom if parent disconnected
function watchdog_clear() {
clearTimeout(watchdog_timer_id);
watchdog_timer_id = setTimeout(function () {
phantom.exit(0);
}, WATCHDOG_TIMEOUT);
}
function lookup(obj, key, value) {
// key can be either string or an array of strings
if (!(typeof obj === 'object')) {
return null;
}
if (typeof key === 'string') {
key = key.split('.');
}
if (!Array.isArray(key)) {
return null;
}
if (arguments.length > 2) {
if (key.length === 1) {
obj[key[0]] = value;
} else {
obj[key[0]] = lookup(typeof obj[key[0]] === 'object' ? obj[key[0]] : {}, key.slice(1), value);
}
return obj;
}
if (key.length === 1) {
return obj[key[0]];
}
return lookup(obj[key[0]], key.slice(1));
}
function page_open (res, page, args) {
page.open.apply(page, args.concat(function (success) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({ data: success }));
res.close();
}));
}
function include_js (res, page, args) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({ data: 'success' }));
page.includeJs.apply(page, args.concat(function () {
try {
res.write('');
res.close();
} catch (e) {
if (!/cannot call function of deleted QObject/.test(e)) { // Ignore this error
page.onError(e);
}
}
}));
}
webserver.listen('127.0.0.1:0', function (req, res) {
// Update watchdog timer on every request
watchdog_clear();
if (req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({ data: callback_stack }));
callback_stack = [];
res.close();
} else if (req.method === 'POST') {
var request, error, output;
try {
request = JSON.parse(req.post);
} catch (err) {
error = err;
}
if (!error) {
if (request.page) {
if (request.method === 'open') { // special case this as it's the only one with a callback
return page_open(res, pages[request.page], request.args);
} else if (request.method === 'includeJs') {
return include_js(res, pages[request.page], request.args);
}
try {
output = pages[request.page][request.method].apply(pages[request.page], request.args);
} catch (err) {
error = err;
}
} else {
try {
output = global_methods[request.method].apply(global_methods, request.args);
} catch (err) {
error = err;
}
}
}
res.setHeader('Content-Type', 'application/json');
if (error) {
res.statusCode = 500;
res.write(JSON.stringify(error));
} else {
res.statusCode = 200;
res.write(JSON.stringify({ data: output }));
}
res.close();
} else {
throw 'Unknown request type!';
}
});
var callbacks = [
'onAlert', 'onCallback', 'onClosing', 'onConfirm', 'onConsoleMessage', 'onError', 'onFilePicker',
'onInitialized', 'onLoadFinished', 'onLoadStarted', 'onNavigationRequested',
'onPrompt', 'onResourceRequested', 'onResourceReceived', 'onResourceTimeout', 'onResourceError', 'onUrlChanged',
// SlimerJS only
'onAuthPrompt'
];
function setup_callbacks (id, page) {
callbacks.forEach(function (cb) {
page[cb] = function (parm) {
var args = Array.prototype.slice.call(arguments);
if ((cb === 'onResourceRequested') && (parm.url.indexOf('data:image') === 0)) {
return;
}
if (cb === 'onClosing') { args = []; }
callback_stack.push({ 'page_id': id, 'callback': cb, 'args': args });
};
});
// Special case this
page.onPageCreated = function (page) {
var new_id = setup_page(page);
callback_stack.push({ 'page_id': id, 'callback': 'onPageCreated', 'args': [ new_id ] });
};
}
function setup_page (page) {
var id = page_id++;
page.getProperty = function (prop) {
return lookup(page, prop);
};
page.setProperty = function (prop, val) {
// Special case for `paperSize.header.contents` property.
if (prop === 'paperSize.header.contents' && val) {
val = phantom.callback(eval('(' + val + ')'));
} else if (prop === 'paperSize.header' && val.contents) {
val.contents = phantom.callback(eval('(' + val.contents + ')'));
} else if (prop === 'paperSize' && val.header && val.header.contents) {
val.header.contents = phantom.callback(eval('(' + val.header.contents + ')'));
}
// Special case for `paperSize.footer.contents` property.
if (prop === 'paperSize.footer.contents' && val) {
val = phantom.callback(eval('(' + val + ')'));
} else if (prop === 'paperSize.footer' && val.contents) {
val.contents = phantom.callback(eval('(' + val.contents + ')'));
} else if (prop === 'paperSize' && val.footer && val.footer.contents) {
val.footer.contents = phantom.callback(eval('(' + val.footer.contents + ')'));
}
lookup(page, prop, val);
return true;
};
page.setFunction = function (name, fn) {
page[name] = eval('(' + fn + ')');
return true;
};
pages[id] = page;
setup_callbacks(id, page);
return id;
}
var global_methods = {
setProxy: function (ip, port, proxyType, user, password) {
return phantom.setProxy(ip, port, proxyType, user, password);
},
createPage: function () {
var page = webpage.create();
var id = setup_page(page);
return { page_id: id };
},
injectJs: function (filename) {
return phantom.injectJs(filename);
},
exit: function (code) {
return phantom.exit(code);
},
addCookie: function (cookie) {
return phantom.addCookie(cookie);
},
clearCookies: function () {
return phantom.clearCookies();
},
deleteCookie: function (name) {
return phantom.deleteCookie(name);
},
getProperty: function (prop) {
return lookup(phantom, prop);
},
setProperty: function (prop, value) {
lookup(phantom, prop, value);
return true;
}
};
// Start watchdog timer
watchdog_clear();
/*eslint-disable no-console*/
console.log('Ready [' + system.pid + '] [' + webserver.port + ']');
// Error class
//
// Based on:
// http://stackoverflow.com/questions/8458984/how-do-i-get-a-correct-backtrace-for-a-custom-error-class-in-nodejs
//
'use strict';
var inherits = require('util').inherits;
function HeadlessError(message) {
// Super constructor
Error.call(this);
// Super helper method to include stack trace in error object
Error.captureStackTrace(this, this.constructor);
// Set our function’s name as error name
this.name = this.constructor.name;
// Set the error message
this.message = message;
}
// Inherit from Error
inherits(HeadlessError, Error);
module.exports = HeadlessError;
{
"author": "Matt Sergeant (matt@hubdoc.com)",
"name": "node-phantom-simple",
"description": "Simple and reliable bridge between Node.js and PhantomJS / SlimerJS",
"version": "2.2.4",
"license": "MIT",
"repository": "baudehlo/node-phantom-simple",
"main": "node-phantom-simple.js",
"files": [
"bridge.js",
"headless_error.js",
"node-phantom-simple.js"
],
"scripts": {
"lint": "./node_modules/.bin/eslint --reset .",
"test": "npm run test-phantom && npm run test-slimer",
"test-phantom": "npm run lint && ./node_modules/.bin/mocha",
"test-slimer": "ENGINE=slimerjs ./node_modules/.bin/mocha"
},
"devDependencies": {
"eslint": "0.24.1",
"eslint-plugin-nodeca": "^1.0.0",
"mocha": "^2.2.5",
"phantomjs": "^1.9.19",
"slimerjs": "~0.9.6"
},
"dependencies": {
"debug": "^2.2.0"
},
"_from": "node-phantom-simple@2.2.4",
"_resolved": "http://registry.npm.taobao.org/node-phantom-simple/download/node-phantom-simple-2.2.4.tgz"
}
\ No newline at end of file
_clone@1.0.2@clone
\ No newline at end of file
_cookies.txt@0.1.2@cookies.txt
\ No newline at end of file
_data-uri-to-buffer@0.0.4@data-uri-to-buffer
\ No newline at end of file
_defaults@1.0.3@defaults
\ No newline at end of file
_node-horseman@3.3.0@node-horseman
\ No newline at end of file
_node-phantom-simple@2.2.4@node-phantom-simple
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment