I'm trying to learn Node and have the function:
this.logMeIn = function(username,stream) {
if (username === null || username.length() < 1) {
stream.write("Invalid username, please try again:\n\r");
return false;
} else {
....etc
and I'm passing it
if (!client.loggedIn) {
if (client.logMeIn(String(data.match(/\S+/)),stream)) {
I've tried both == and ===, but I'm still getting errors as the username is not detecting that it is null, and username.length() fails on:
if (username === null || username.length() < 1) {
^
TypeError: Property 'length' of object null is not a function
I'm sure that Node won't evaluate the second part of the || in the if statement when the first part is true - but I fail to understand why the first part of the if statement is evaluating to false when username is a null object. Can someone help me understand what I've done wrong?
length
is an attribute, not a function. Try username.length
If you require a non-empty string, you can do a simple "truthy" check that will work for null
, undefined
, ''
, etc:
if (username) { ... }
With that approach, you don't even need the .length
check. Also, length
is a property, not a method.
Edit: You have some funkiness going on. I think you need to start with how you're passing in your username - I don't think that your String(data.match(/\S+/))
logic is behaving the way that you're expecting it to (credit to @Engineer for spotting this).
Your match expression is going to return one or two types of values: null
or an Array
. In the case that it's null, as @Engineer pointed out, you end up passing in "null"
as a string, which should resultantly pass your username check later on. You should consider revising this to:
if (!client.loggedIn) {
var matches = data.match(/\S+/);
if (client.logMeIn(matches ? matches[0] : '',stream)) {
Regarding .length
being equal to 1
in all cases - that doesn't honestly make a lot of sense. I would recommend adding a lot of console.log()
statements to try and figure out what's going on.
You're passing String(data.match(/\S+/))
as username
argument, so when data.match(/\S+/)
is null
, you get "null"
not null
for username
, as:
String(null) === "null"
So you need to change your condition:
if( username === null || username === "null" || username.length < 1 )