There are three things going on there:
const
declares a "variable" you can't change the value of (a constant).
By using let
in the inner function, you're shadowing that constant with a local variable. There is no connection whatsoever between the inner local variable and the outer constant.
At the end of your code, where you're logging the value, it will still have its initial value, because it hasn't been changed yet. The event callbacks won't have been called yet. Details on that in the answers to this question and this one.
If you want to add to the outer myString
, use let
to declare it, and don't use let
when referencing it inside the function.
// SEE BELOW AS WELL
const https = require("https");
let myString = ""; // You probably want `""` or `null`, not `"null"`
var request = https.request(options, function (res) {
let data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on("end", function () {
// *** No `let` here
myString = data;
console.log(myString);
});
});
console.log(myString); // You'll still get `""` or `null` here, it isn't updated yet
Notice that I replaced var
with let
or const
, and changed the name of the variable from MyString
to myString
. There's no place for var
in modern JavaScript code, and the overwhelmingly-common naming convention for variables is to start them with a lower case letter (initial caps are used for constructor function names).
But, because of #3 above, you really don't want myString
at all. Instead:
const https = require("https");
var request = https.request(options, function (res) {
let myString = "";
res.on("data", function (chunk) {
myString += chunk;
});
res.on("end", function () {
// *** Just use `myString` here, don't try to use it
// at the top level of your module at all.
console.log(myString);
});
});
Side note: Your code assumes that chunk
will be a string, but I'm not sure that's true with the stream you get from https.request
, but I'm not sure that's true. If so, great, but it may well be a Buffer
object in which case +=
won't work (you'd need concat
or similar).