Fairly new to NodeJs (however not to Javascript) and I think it is great, not in all aspects but that is not the subject of the question.
Found this 'feature' by accident, actually it is exactly what I want however don't know it is legit or a bug. What I did in an include file:
// var <- var is now a comment
ksNone = 0,
ksAltKey = 1,
ksCtrlKey = 2,
ksShiftKey = 4;
......
.......
When traversing the global object in the main file, with code below ...
code:
require( './lib/mycode.js' );
for( var p in global )
{ console.log( p ); }
.... you will finally see:
output:
........ <- many other vars
........
........
ksNone
ksAltKey
ksCtrlKey
ksShiftKey
Made me thinking, it not easy to include a file with a bunch of functions for general purpose. For example, I have some functions to validate strings and numbers and all kind of other stuff that doesn't need to be in a namespace or class. Normally, to include such functions you have to specify exports for it or include it in a hacky way via fs and eval() - see also this question.
I tried the the following:
code:
ksNone = 0,
ksAltKey = 1,
ksCtrlKey = 2,
ksShiftKey = 4,
isNumber = function( i )
{
return typeof i === 'number' && isFinite(i) && !isNaN(i);
},
isValidNumber = function( i, iMin, iMax )
{
if( !isNumber( i ) )
{ return false; }
if( isNumber( iMin ) && i < iMin )
{ return false; }
if( isNumber( iMax ) && i > iMax )
{ return false; }
return true;
},
isString = function( a )
{
return ( typeof a === 'string' || ( a instanceof String ));
},
isValidString = function( s, iMinLen, iMaxLen )
{
if( isString( s ) )
{
var iLen = s.length,
bIsMin = ( isNumber( iMinLen ) && iMinLen >= 0 )?(iLen >= iMinLen):(iLen > 0),
bIsMax = ( isNumber( iMaxLen ) && iMaxLen >= 0 )?(iLen <= iMaxLen):(iLen > 0);
return ( bIsMin && bIsMax );
}
return false;
};
And traversing again will now output:
output:
........ <- many other vars
........
........
ksNone
ksAltKey
ksCtrlKey
ksShiftKey
isNumber
isValidNumber
isString
isValidString
Once included, because it is now in the global scope, I can do this everywhere:
code:
var test = "yes"
if( isValidString( test ) ) // call the global function
{ console.log( "String is valid" ); }
output:
String is valid
questions:
Normally it is not a good idea to left out declaration stuff such as var
(it doesn't work in strict mode - "use strict";
) however in this case it seems to be very handy because you don't need to specify exports or use a hacky way to include it and those functions are globally accessable without a namespace or const/var require declaration.
What actually happen when you include a file? Scans the NodeJs core consts, vars, functions to keep it private? Is it legit to use or is it a bug? A do or don't, what do you think?