From 60a9dc2470b319902c9d87230a3ab62604520a73 Mon Sep 17 00:00:00 2001 From: "David Humphrey (:humph) david.humphrey@senecacollege.ca" Date: Wed, 26 Mar 2014 19:34:32 -0400 Subject: [PATCH] Beef up XHR code in sh.wget(), still failing 2 in PhantomJS due to not having web server --- src/shell/shell.js | 19 +++++++++++++++---- tests/spec/shell/wget.spec.js | 11 +++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/shell/shell.js b/src/shell/shell.js index e5d392a..3a1f7e0 100644 --- a/src/shell/shell.js +++ b/src/shell/shell.js @@ -444,8 +444,16 @@ define(function(require) { var path = options.filename || ('file-' + Date.now()); path = Path.resolve(fs.cwd, path); + function onerror() { + callback(new Error('unable to get resource')); + } + var request = new XMLHttpRequest(); - request.addEventListener("load", function() { + request.onload = function() { + if(request.status !== 200) { + return onerror(); + } + var data = new Uint8Array(request.response); fs.writeFile(path, data, function(err) { if(err) { @@ -454,9 +462,12 @@ define(function(require) { callback(null, path); } }); - }, false); - request.addEventListener("error", function(err) { callback(err); }, false); - request.open("GET", url); + }; + request.onerror = onerror; + request.open("GET", url, true); + if("withCredentials" in request) { + request.withCredentials = true; + } request.responseType = "arraybuffer"; request.send(); }; diff --git a/tests/spec/shell/wget.spec.js b/tests/spec/shell/wget.spec.js index 3a4b587..3608c8c 100644 --- a/tests/spec/shell/wget.spec.js +++ b/tests/spec/shell/wget.spec.js @@ -20,6 +20,17 @@ define(["Filer", "util"], function(Filer, util) { }); }); + it('should fail when the url does not exist (404)', function(done) { + var fs = util.fs(); + var shell = fs.Shell(); + + shell.wget("no-such-url", function(err, data) { + expect(err).to.exist; + expect(data).not.to.exist; + done(); + }); + }); + it('should download the contents of a file from a url to default filename', function(done) { var fs = util.fs(); var shell = fs.Shell();