Reputation: 37
I am new to Node.js.
I am getting data from some other servers via Node.js:
function get_data(data_url, a, callback) {
console.log('dataurl = ' + data_url);
rem_url = url.parse(data_url);
console.log('hostname = ' + rem_url.hostname);
console.log('host = ' + rem_url.host);
console.log('path = ' + rem_url.path);
options = {
hostname: rem_url.hostname,
path: rem_url.path,
keepAlive: true
};
request = http.request(options, function (res) {
data = '';
res.on('data', function (chunk) {
data = data + chunk;
sleep(20);
});
res.on('end', function () {
callback(a, data);
});
res.on('error', function (err) {
console.log("Error Occurred: " + err.message);
});
});
request.on('error', function (e) {
console.log('dataurl = ' + data_url);
console.log('a = ' + a);
console.log('problem with request: ' + e.message);
});
request.end();
}
I was getting broken data so I inserted a sleep function:
res.on('data', function (chunk) {
data = data + chunk;
sleep(20);
});
I am still wondering if there is a better way? Thank you very much!
Note: this is my sleep function:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
More details :
Upvotes: 1
Views: 113
Reputation: 658
while reading your codes i noticed that even there same comments,
you need to set data inside function not outside.
so it becomes local variable.
in your function data variable is global.
Because you get better results with sleep() function; javascript needs some time to overwrite global data.that is explaning why you get better results .
just write like this and delete var data;
from upper lines of js file.
var data = '';
res.on('data', function (chunk) {
data = data + chunk;
});
Upvotes: 1