2

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);
3
  • 1
    You're working with asynchronous code; you have to do your logic inside the callback, or use promises. Commented Aug 26, 2014 at 17:37
  • There are two reasons that the variable doesn't change. You don't change it anywhere in the code, and the code is asynchronous so if you did change it, you would log it before you changed it. Commented Aug 26, 2014 at 17:39
  • Is there a way to assign content inside that function and use it later? Or do I just have to have another function that waits till it populates and then run that inside my http.get? Commented Aug 27, 2014 at 17:06

2 Answers 2

1

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);
     }));
   });
Sign up to request clarification or add additional context in comments.

1 Comment

yes at first but now I want to use content outside of http.get. But I need to assign it value inside http.get to use later.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.