1

My variable "whole" is undefined.

getStudents.js

var http = require('http');

module.exports = {
'sendResults': function(){
    http.get(' http://gs-class.com/nodejs/students.php', function(res){
    var whole = '';
    res.on('data',function(chunk){
        whole+=chunk;
    });
    res.on('end', function(){
        return whole;
    });
    });
    }
}

studWrite.js

var getStudents = require('./getStudents');
var fs = require('fs');
var results = getStudents.sendResults();
console.log(results);

and when I am running the program studWrite.js my var 'whole' is undefined. pls help.

Ulukbek Abylbekov
  • 449
  • 1
  • 6
  • 19
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Mar 22 '17 at 08:29
  • You are returning from a callback. – Rajesh Mar 22 '17 at 08:30

1 Answers1

1

Try this:

studWrite.js

var getStudents = require('./getStudents');
var fs = require('fs');
getStudents.sendResults(function(result) {
    console.log(result);
});

getStudents.js

var http = require('http');

    module.exports = {
        'sendResults': function(callback) {
            http.get(' http://gs-class.com/nodejs/students.php', function(res) {
                var whole = '';
                res.on('data', function(chunk) {
                    whole += chunk;
                });
                res.on('end', function() {
                    callback(whole)
                });
            });
        }
    }

You need to use asynchronous approach (Callbacks, Promises) to resolve the issue.

  • working!!! Thnx. I am new in node.js so I have to research your code better – Ulukbek Abylbekov Mar 22 '17 at 08:45
  • @UlukbekAbylbekov you should have strong knowledge of Asynchronous programming before writing Node.js. Anyway. if this works for you, please accept the answer. –  Mar 22 '17 at 10:00