I'm trying to convert the following Node.js snippet to Dart. In my conversion the 'data returned...' message is printed as soon as there is a response unlike in the Node.js version which waits until the page completes the requested 2 second delay.
Node.js
var http = require('http')
function fetchPage() {
console.log('fetching page');
http.get({ host: 'trafficjamapp.herokuapp.com', path: '/?delay=2000' }, function(res) {
console.log('data returned from requesting page');
}).on('error', function(e) {
console.log("There was an error" + e);
});
}
Dart
import 'dart:io';
import 'dart:uri';
fetchPage() {
print('fetching page');
var client = new HttpClient();
var uri = new Uri.fromComponents(scheme:'http', domain: 'trafficjamapp.herokuapp.com', path: '?delay=2000');
var connection = client.getUrl(uri);
connection.onRequest = (HttpClientRequest req) {
req.outputStream.close();
};
connection.onResponse = (HttpClientResponse res){
print('data returned from requesting page');
};
connection.onError = (e) => print('There was an error' ' $e');
}
How do I achieve the same delayed print in Dart as in Node? Thanks in advance.
You can find this in the documentation of the onResponse
callback:
The callback is called when all headers of the response are received and data is ready to be received.
So it works like this:
connection.onResponse = (res) {
print('Headers received, can read the body now');
var in = res.inputStream;
in.onData = () {
// this can be called multiple times
print('Received data');
var data = in.read();
// do something with data, probably?
};
in.onClosed = () {
// this is probably the event you are interested in
print('No more data available');
};
in.onError = (e) {
print('Error reading data: $e');
};
};
Your Dart code was almost right, but there was a bug. You should have used query
named parameter instead of path
. I don't really know which Url is call with your code but the response has a 400
status code. For more readability, you can also use the Uri.fromString
constructor.
Moreover you can omit your onRequest
setting because the same code is done when onRequest
is not defined.
Here's the code :
import 'dart:io';
import 'dart:uri';
main() {
print('fetching page');
//var uri = new Uri.fromString('http://trafficjamapp.herokuapp.com/?delay=2000');
var uri = new Uri.fromComponents(scheme:'http',
domain: 'trafficjamapp.herokuapp.com', query: 'delay=2000');
var client = new HttpClient();
var connection = client.getUrl(uri);
connection.onResponse = (HttpClientResponse res){
print('data returned from requesting page with status ${res.statusCode}');
};
connection.onError = (e) => print('There was an error' ' $e');
}