Newbie question about avoiding global variables

H

hukash

Hi everyone,

I lately started playing around with javascript (node.js) and got
stuck avoiding global variables. I hope someone can tell me what I'm
doing wrong.

Here's my script:
---
var sys = require('sys'),
fs = require('fs');

var FileReader = {

directory: null,
result: null,
tempDir:null,

start: function (directory) {
this.directory = directory;

this.tempDir = this.checkDirectory (this.directory);
this.result = this.readDirectory (this.directory);

sys.puts("Directory: " + this.tempDir); // output is undefined
sys.puts("Result: " + this.result); // output is undefined

},

checkDirectory: function(directory) {
fs.stat(directory, function (err, stats) {
if (err) throw err;

if (stats.isDirectory()) {
return directory;
} else {
return false;
}
});
},

readDirectory: function (directory) {
fs.readdir(directory, function (err, files) {
if (err) throw err;
return files;
});
},
};

FileReader.start("/Users");
---

this.tempDir and and this.directory are both undefined. So far I can
tell, the functions checkDirectory and readDirectory are working fine.
How do I assign the results of both functions correctly?

Thanks in advance,
Luke
 
T

Thomas 'PointedEars' Lahn

hukash said:
I lately started playing around with javascript (node.js) and got

There is no "javascript".

stuck avoiding global variables. I hope someone can tell me what I'm
doing wrong.

Here's my script:
---
var sys = require('sys'),
fs = require('fs');

var FileReader = {

directory: null,
result: null,
tempDir:null,

start: function (directory) {
this.directory = directory;

this.tempDir = this.checkDirectory (this.directory);
this.result = this.readDirectory (this.directory);

sys.puts("Directory: " + this.tempDir); // output is undefined
sys.puts("Result: " + this.result); // output is undefined

},

checkDirectory: function(directory) {
fs.stat(directory, function (err, stats) {
if (err) throw err;

The unescaped `throw' statement makes your code not backwards-compatible.
if (stats.isDirectory()) {
return directory;
} else {
return false;
}
});
},

readDirectory: function (directory) {
fs.readdir(directory, function (err, files) {
if (err) throw err;
return files;
});
},
};

FileReader.start("/Users");

No, `this.tempDir' and `this.result' have the undefined value, which string
representation, "undefined", is probably put out by your host-defined or
user-defined method sys.puts() we can know nothing about.
So far I can tell, the functions checkDirectory and readDirectory are
working fine. How do I assign the results of both functions correctly?

You forgot to let FileReader.checkDirectory() and
FileReader.readDirectory() return something different from the `undefined'
value to their callers, so their return value is the `undefined' value.

The `return' statements you have are within the function that you pass to
fs.stat() and fs.readdir(), respectively. fs.stat() and fs.readdir() need
to return those return values, so that FileReader.checkDirectory() and
FileReader.readDirectory() can return them to their callers, respectively.

Some recommendations as to code style:

- You should not choose identifiers starting with a capital letter for
non-constructors or non-constants.

- You should remove the white-space between the /MemberExpression/ and the
/ArgumentList/ in the /CallExpression/; include it only when an operand
needs to be parenthesized, e.g. `typeof (foo = x.bar) != "undefined"',
to distinguish method calls from operations.

- Remove the trailing comma from the /ObjectLiteral/ as it is not
interoperable.


PointedEars
 
L

Lasse Reichstein Nielsen

hukash said:
I lately started playing around with javascript (node.js) and got
stuck avoiding global variables. I hope someone can tell me what I'm
doing wrong. ....
this.tempDir = this.checkDirectory (this.directory);
this.result = this.readDirectory (this.directory);

sys.puts("Directory: " + this.tempDir); // output is undefined
sys.puts("Result: " + this.result); // output is undefined

This means that this.checkDirectory and this.readDirectory returns undefined.
checkDirectory: function(directory) {
fs.stat(directory, function (err, stats) {
if (err) throw err;

if (stats.isDirectory()) {
return directory;
} else {
return false;
}
});
},

You don't return any value from this function.

I'm guessing this is the node.js fs module, and if so, the call to
stat is asynchroneous. You need to either properly chain the execution of
the asynchromeous operations. Something like:
checkDirectory: function(directory, continuation) {
fs.stat(directory, function (err,stats) {
if (err) throw err;
if (stats.isDirectory()) {
continuation(directory);
} else {
continuation(false);
}
});
},

and call it as:

var self = this;
this.checkDirectory(directory, function(tempDir) {
self.tempDir = tempDir;
self.readDirectory(directory, function(result) {
self.result = result;
// ... continue program.
})
});

Alternatively, you could use the synchroneous versions:

checkDirectory: function (directory) {
var stats = fs.statSync(directory);
return stats.isDirectory() ? directory : false;
},
readDirectory: function (directory) {
fs.readdir(directory, function (err, files) {

Ditto here.

/L
 
S

Sean Kinsey

The unescaped `throw' statement makes your code not backwards-compatible.

And why should one expect V8 (the VM running NodeJS) to suddenly
regress failing to support throw?
 
T

Thomas 'PointedEars' Lahn

Antony said:
That's not helpful since 2.1 states `The term "javascript"
is used as a common name for all dialects of ECMAScript.'

That's a bug.
And the OP specifies the implementation.

They don't.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Sean said:
And why should one expect V8 (the VM running NodeJS) to suddenly
regress failing to support throw?

"node.js" can be *anything*.


PointedEars
 
R

Richard Cornford

Thomas 'PointedEars' Lahn :

I disagree. Plain "javascript" (not "JavaScript") is widely used
that way,

The statement in the FAQ would be true if there was only a single
example of "javascript" being used in that way. However, "javascript"
is widely used in that way.
cf. MIME types, and is readily understood. It seems to me that
Brendan Eich has a point when he says that "ECMAScript" sounds
like a skin disease.

There is also always the matter of connecting with the people who
don't know any better; the ones who are just starting out and have no
idea of what ECMAScript is. While employing the well (and objectively)
defined terminology from the specification is valuable for making
precise statements about javascript the result of taking that to an
extreme (or insisting on their exclusive use) would leave everyone
involved talking their own esoteric language, and incomprehensible to
the uninitiated.

Richard.
 
T

Thomas 'PointedEars' Lahn

Johannes said:
Thomas 'PointedEars' Lahn :

I disagree.

It is pure invention by those who don't know better or don't want to know
better.
Plain "javascript" (not "JavaScript") is widely used that way,
cf. MIME types, and is readily understood. It seems to me that Brendan
Eich has a point when he says that "ECMAScript" sounds like a skin
disease.

The point is that without telling about the runtime environment the term
"javascript" as a replacement term is pretty useless as statement made
about it can be both completely right and completely wrong, and source code
presented to be "javascript" code can be both syntactically correct and
incorrect, working and not working, concepts described with it correctly or
incorrectly, all depending on the runtime environment. Further, the term
promotes the common misconception that there would be only one language
with "dialects", where the diversity is clearly a lot greater than this.

Referring to Brendan Eich in this matter and manner is an argument at
authority -- obviously fallacious. Even Brendan Eich can be wrong, and the
fact that he thinks "ECMAScript" sounded like a skin disease (and I do not
subscribe to that opinion) bears no relevance on the (in)correctness and
(lacking) precision of the term "javascript".


PointedEars
 
T

Thomas 'PointedEars' Lahn

Richard said:
The statement in the FAQ would be true if there was only a single
example of "javascript" being used in that way. However, "javascript"
is widely used in that way.

The main problem with it is a) that it is not generally used as a
replacement term for "ECMAScript implementation" (the term "dialects of
ECMAScript" is plain *wrong*), and b) that the lack of capital characters
is insufficient to make a considerable difference.
[...] It seems to me that Brendan Eich has a point when he says that
"ECMAScript" sounds like a skin disease.

There is also always the matter of connecting with the people who
don't know any better; the ones who are just starting out and have no
idea of what ECMAScript is. While employing the well (and objectively)
defined terminology from the specification is valuable for making
precise statements about javascript the result of taking that to an
extreme (or insisting on their exclusive use) would leave everyone
involved talking their own esoteric language, and incomprehensible to
the uninitiated.

On the other hand, not pointing out that they are (probably) using an
implementation of ECMAScript which depends on the environment the code
eventually runs in instead of a single language named "javascript" that
would work the same everywhere (which in common use of the term often
includes DOM implementations) leaves the people who don't know any better
in the dark (especially when miseducated by books) and causes all kinds of
misconceptions and misunderstandings in the process (like "$BROWSER is
broken" when it simply supports another implementation, or another DOM
implementation with its bound objects complying with the ECMAScript
Specification).


PointedEars
 
S

Sean Kinsey

"node.js" can be *anything*.

If you are unable to deduct that "javascript (node.js)" refers to
"javascript as in the one used in node.js, as in the _name_
"node.js" (http://nodejs.org), as in V8, as in ECMA-262, 3rd edition",
then you are thicker than I thought.
 
J

Jorge


Except for the brain-damaged, ("JaVaScRiPt".toLowerCase() ==
"eCmAsCrIpT".toLowerCase()) yields a big true :)
You should append a ™ when referring to mozilla's implementation:
JavaScript™.
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
That's a bug.

If the whole world disagrees with you ... it must be them who are wrong!
They don't.

He did. That you don't recognize it doesn't mean that it wasn't there.
The node.js environment counts as a specific javascript implementation
and environment, based on the V8 engine.

/L
 
J

Jonathan Fine

hukash said:
Hi everyone,

I lately started playing around with javascript (node.js) and got
stuck avoiding global variables. I hope someone can tell me what I'm
doing wrong.

Hello hukash. I hope you found help in the responses to this thread.

(I've glanced at it and found it mostly off-topic.)
 
T

Thomas 'PointedEars' Lahn

Lasse said:
If the whole world disagrees with you ... it must be them who are wrong!

Argument at the silent majority.
He did. That you don't recognize it doesn't mean that it wasn't there.
The node.js environment counts as a specific javascript implementation
and environment, based on the V8 engine.

It is inference, not deduction, that lead you to believe that "node.js"
means that one library that only runs on that one script engine. AISB,
"node.js" can be anything.

Therefore, The OP's postings should have started like "I have tried the
following code using node.js in Google Chrome ...".


PointedEars
 
S

Sean Kinsey

Argument at the silent majority.



It is inference, not deduction, that lead you to believe that "node.js"
means that one library that only runs on that one script engine.  AISB,
"node.js" can be anything.

Therefore, The OP's postings should have started like "I have tried the
following code using node.js in Google Chrome ...".

You are clearly not familiar with what node.js is, nor have you taken
the time to enlighten your self..
 
J

Jorge

It is inference, not deduction, that lead you to believe that "node.js"
means that one library that only runs on that one script engine.

It's not a library genius.
 
H

hukash

Hello hukash.  I hope you found help in the responses to this thread.

(I've glanced at it and found it mostly off-topic.)

Whoopsy, it wasn't my intention to start a debate on principles.
Whatever, I don't care why someone wouldn't call it javascript, since
the newsgroup is named comp.lang.JAVASCRIPT and not comp.lang.ECMA262.

Sorry for the misleading subject. I started to play around by using
global variables and everything seemed to work fine. Then I looked up
how to create objects and avoiding global vars and my script failed.

Or did you find it off-topic because I'm using node.js?

Thanks to Lasse, I used the given synchronous example and now it works
how I it was intended to. Maybe learning javascript with node.js is
not the best/easiest way ;-)

Thanks for the help.
Hukash
 
S

Sean Kinsey

Whoopsy, it wasn't my intention to start a debate on principles.
Whatever, I don't care why someone wouldn't call it javascript, since
the newsgroup is named comp.lang.JAVASCRIPT and not comp.lang.ECMA262.

Sorry for the misleading subject. I started to play around by using
global variables and everything seemed to work fine. Then I looked up
how to create objects and avoiding global vars and my script failed.

Or did you find it off-topic because I'm using node.js?

Thanks to Lasse, I used the given synchronous example and now it works
how I it was intended to. Maybe learning javascript with node.js is
not the best/easiest way ;-)

Thanks for the help.
Hukash

The direction the discussion took has little to do with the original
subject being off-topic or anything, its actually quite common here.

To me it seems that ECMA-262 is more like a compulsive disorder to
some people than a tool used to create value.
Just because you test all code in IE5 doesn't mean that you should (or
is in any position) to look down on those who don't. Some people
actually does cost/benefit analyses on what browsers to target you
know.. Starting every discussion with the notion that everyone else
are morons, know nothing, and that they cannot have though anything
through, is quite the character flaw if you ask me...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top