I'm still trying to get the hang of this, but this is confusing for me. So I use http.get and a pipe with the bl module, I want it to change content so I can use it outside the function doesn't work why? I thought with var it would be global within my file and that would allow me to change it.
var http = require('http');
var bl = require('bl');
var url1 = process.argv[2];
var content;
http.get(url1, function(response){
response.pipe(bl(function(err,data){
return data.toString();
}));
});
console.log(content.length);
console.log(content);
Are you trying to modify content
? You never assign anything to it and then you try to access it synchronously (which will almost certainly occur before the get
completes). I assume you want to do something more like:
...
var content;
http.get(url1, function(response){
response.pipe(bl(function(err,data){
content = data.toString();
console.log(content.length);
console.log(content);
}));
});
Node.js is asynchronous, which means that your code beneath your get
function will probably get executed BEFORE the code inside your callback function (the function you pass as the second argument).
var http = require('http');
var bl = require('bl');
var url1 = process.argv[2];
var content;
http.get(url1, function(response){
response.pipe(bl(function(err,data){
// After all callbacks have come back, modify content
content = data.toString(); // Set the value of content
console.log(content.length);
console.log(content);
return content;
}));
});
// The callback function in get still hasn't been called!
console.log(content); // undefined