SetV SetV - 3 months ago 68
AngularJS Question

AngularJS with StreamSaver.js Support

I want to add the following StreamSaver.js code to an AngularJS. The same syntax is not accepted so I have changes the code to suite angular.

I got the following

WritableStream is not defined
error.

angular-1.5.7.min.js:117 ReferenceError: WritableStream is not defined
at Object.createWriteStream (StreamSaver.js:92)
at m.$scope.downloadFile (profile_ctrl.js:305)


The StreamSaver Example code is working fine.

fetch(url).then(res => {
let reader = res.body.getReader()
let pump = () => {
return reader.read().then(({ value, done }) => {
if (done) {
myFile.close()
return
}
myFile.write(value)
return pump()
})
}
pump()
})


Whereas not the modified code given below.

var myFile = streamSaver.createWriteStream("filename.txt");
fetch(url).then(function(res) {
$scope.pump = function(reader) {
return reader.read().then(function(value, done) {
if (done) {
myFile.close();
return;
}
myFile.write(value);
return pump();
});
};
var reader = res.body.getReader();
$scope.pump(reader);
});

Answer

The error is because of ES6 syntax. The following code works for ES5 in chrome v52 browser.

var myFile = streamSaver.createWriteStream("filename.txt");

fetch(url).then(function(res) {
  var reader = res.body.getReader();
  $scope.pump(reader);
});

$scope.pump = function(reader) {
  return reader.read().then(function(result) {
    if (result.done) {
      myFile.close();
      return;
    }
    myFile.write(result.value);
    return $scope.pump(reader);
  });
};