Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sneha: Total 1 minute -- 29299ms highest #39

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 60 additions & 6 deletions crawler.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Created by tushar on 13/09/17.
* Created by Sneha on 16/09/17.
*/

'use strict'
Expand All @@ -9,10 +9,64 @@
* @param url
* @return {Promise.<string>}
*/

const request = require("request");
var http = require('http');
var httpAgent = new http.Agent({keepAlive:true, keepAliveMsecs:30000, maxSockets: 50});

const getMatches = (str, regex) => {
let m = [];
const matches = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
if (groupIndex === 1)
matches.push(match);
});
}
return matches;
}

module.exports = url =>
new Promise((resolve, reject) => {
/**
* TODO: Write your high performance code here.
*/
reject(new Error('NotImplemented'))
})

let start = new Date();
let tags = [];
const baseURL = url;
let linkCount = 1;
let resolvedCount = 0;
const linksTouched = {};
const linkRegex = /href="(.*?)"/g;
const tagRegex = /<h1>(.*?)<\/h1>/g;

const getBest = async (url) => {
request({url, pool: httpAgent}, (error, response, body) => {

if(error || (response && response.statusCode != 200)) {
console.log('error '+error)
getBest(url);
return;
}
resolvedCount++;
const linkList = getMatches(body, linkRegex).map(link => link.substr(0, 1) == '/' ? baseURL + link : link);
tags.push(getMatches(body, tagRegex).sort()[0]);

linkList.forEach((link) => {
if (!linksTouched[link]) {
linksTouched[link] = true;
linkCount++;
getBest(link);
}
});

if (resolvedCount == linkCount) {
resolve(tags.sort()[0])
}
})
}
getBest(url);
});
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"express-rate-limit": "^2.9.0",
"mocha": "^3.5.3",
"nodemon": "^1.12.0",
"pug": "^2.0.0-rc.4"
"pug": "^2.0.0-rc.4",
"request": "^2.81.0"
}
}