// Dependencies
var fs = require('fs');
var url = require('url');
var http = require('http');
var jsdom = require("jsdom");
var exec = require('child_process').exec;

var thread = process.argv[2];
var host = url.parse(thread);
var folderName = host.pathname.split('/').pop();
var mkdir = 'mkdir -p ' + 'downloads/' + folderName;
var chmod = 'chmod -R 777 downloads/' + folderName;

var mkdirExec = exec(mkdir, function (err, stdout, stderr) {
    if (err) {
        throw err;
    } else {
        console.log('folder created');
    }
});
var chmodExec = exec(chmod, function (err, stdout, stderr) {
    if (err) {
        throw err;
    }
});

var links = [];

jsdom.env(
    thread,
    ["http://code.jquery.com/jquery.js"],
    function (err, window) {
        images = window.$(".postContainer .file .fileThumb");
        for (i = 0; i < images.length; i++) {
            links.push(window.$(images[i]).attr('href'));
        }
       for (i = 0; i < links.length;i++) {
           href = 'http://'+links[i].replace(/\/\//, '');
           splitted = href.split("/");
           filename = splitted[splitted.length - 1];

           var request = http.get(href, function(res){
               var imagedata = '';
               res.setEncoding('binary');

               res.on('data', function(chunk){
                   imagedata += chunk
               });

               res.on('end', function(){
                   fs.writeFile(filename, imagedata, 'binary', function(err){
                       if (err) {
                           throw err
                       }
                       console.log(filename + ' saved.')
                   });
               })
           })
       }
    }
);


@@ -13,32 +13,8 @@
 ies%0A
-var fs = require('fs');%0A
 var 
@@ -59,16 +59,24 @@
 re('http
+-request
 ');%0Avar 
@@ -1102,17 +1102,16 @@
 h - 1%5D;%0A
-%0A
         
@@ -1117,337 +1117,136 @@
     
-var request = http.get(href, function(res)%7B%0A               var imagedata = '';%0A               res.setEncoding('binary');%0A%0A               res.on('data', function(chunk)%7B%0A                   imagedata += chunk%0A               %7D);%0A%0A               res.on('end', function()%7B%0A                   fs.writeFile(filename, imagedata, 'binary'
+fullPath = 'downloads/' + folderName + '/' + filename;%0A%0A           options = %7Burl: href%7D;%0A%0A           http.get(options, fullPath
 , fu
@@ -1255,18 +1255,27 @@
 tion
+ 
 (err
-)%7B%0A   
+or, result) %7B%0A
     
@@ -1289,20 +1289,17 @@
     
-     
 if (err
+or
 ) %7B%0A
@@ -1317,33 +1317,37 @@
         
-        throw err
+console.error(error);
 %0A       
@@ -1354,30 +1354,25 @@
         
-        %7D%0A    
+%7D else %7B%0A
         
@@ -1398,50 +1398,44 @@
 log(
-filename + ' saved.')%0A                   %7D
+'File downloaded at: ' + result.file
 );%0A 
@@ -1441,33 +1441,32 @@
                %7D
-)
 %0A           %7D)%0A 
@@ -1463,16 +1463,17 @@
       %7D)
+;
 %0A       

use http-request because...