0

Can someone please explain why some variables are not passed to readFile's callback, while others are?

// response is http response writer obj
var process = function (response, file) {

    var calculator = new mycalc.Calculator();

    var output1 = "no-error";
    var that = this;

    try {
        fs.readFile(file, 'utf8', function (err, data) {
            if (err) {
                that.output1 = "check1";
            }

            output1 = "check2";
            response.write(output1);

            // not even working with that.output1

            // more stuff will come here
        });
    } catch (e) {
        response.write(e.stack);
    }

    response.write(output1);
};


Issues:

  • response.write() doesn't write within the callback function but it does write successfully from process() function scope.

  • output1 prints "no-error", while the expected result is "check1" or "check2"

Annie
  • 3,090
  • 9
  • 36
  • 74
  • 2
    They are all in the scope, but you are calling `response.write(output1)` before the `fs.readFile` callback is executed. – Felix Kling Jul 01 '14 at 23:24
  • @FelixKling, is `response` in the scope too? When I do `response.write("foo");` within callback, it doesn't get printed in the browser. When I do it outside, it does. Maybe its not as simple as it seems.. – Annie Jul 02 '14 at 00:06
  • It should just work like that. Every JS function is a closure and has access to all variables that are defined in the same or higher scope. It might be an issue with how `process` is supposed to be used. – Felix Kling Jul 02 '14 at 00:10

0 Answers0