Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a nodejs stream in angular?

In nodejs I send a stream to clients like this:

DockerService.get().pull('my/image', function(err, stream) {
  if (err) {
    return res.badRequest(err);
  } else {
    return stream.pipe(res);
  }
});

This is triggered from a angularjs client using $http.get:

pull: function() {
  var url = ENV.apiEndpoint + '/docker/pull';
  var promise = $http.get(url).success(function(response) {
    return response;
  }).error(function(data, status) {

  });
  return promise;
}

However I cannot read the stream. From angular I get an error message:

SyntaxError: Unexpected token {
    at Object.parse (native)
    at fromJson (file://build/vendor/angular/angular.js:1065:14)
    at defaultHttpResponseTransform (file://build/vendor/angular/angular.js:8579:16)
    at file://build/vendor/angular/angular.js:8664:12
    at forEach (file://build/vendor/angular/angular.js:323:20)
    at transformData (file://build/vendor/angular/angular.js:8663:3)
    at transformResponse (file://build/vendor/angular/angular.js:9389:23)
    at processQueue (file://build/vendor/angular/angular.js:13189:27)
    at file://build/vendor/angular/angular.js:13205:27
    at Scope.$get.Scope.$eval (file://build/vendor/angular/angular.js:14401:28)

I cannot find any information on how to handle streams in angular. Can you help me out?

Headers:

enter image description here

The response is too large to present it here, so here is the first part of it:

enter image description here

Preview:

enter image description here

like image 890
UpCat Avatar asked Mar 08 '15 17:03

UpCat


1 Answers

So that's not valid JSON, it's a series of newline-delimited (presumably) JSON messages. That's what the "unexpected token '{'" means. Angular's built-in parser doesn't support that out of the box. The question isn't really about streaming vs. buffered data, it's just a body format angularjs doesn't directly support. You'll need to ensure angular's built-in parser is bypassed and then you can split the string on newline and try/catch parsing each line as a JSON object.

FYI to my knowledge the best module for streaming into the browser is oboe.js. You may be able to use RonB/angular-oboe coupled with some code to buffer each line then parse the ndjson syntax into a stream of JS objects.

like image 170
Peter Lyons Avatar answered Oct 16 '22 03:10

Peter Lyons