0

I'm coding a simple chat browser application with Node.js. To keep multiple users from using the same name, I store all user's names in an array

userList.push(socketName);

and every time someone connects, I look for his name in this array

function inList(name, list) {
  if(list.indexOf(name) === -1)
    return false;
  return true;
}

This work perfectly. My problem is I also want to check a white list in an external text file, which have a single name per line. My code for that is

let temp = fs.readFileSync('./list.txt', 'UTF-8');
var whiteList = temp.split('\n');
if(inList(socketName, whiteList)) {
   //let user join
}

It is the same logic, I'm just loading the list from a file. In this case, function inList() will return true only if the name tested is in the last line of the file. Any of the other names in the list will cause it to return false, and I have no idea why.

I thought the string.split('\n') could leave the '\n' on the returned array, so I tried printing all whiteList[] elements on console and on another file and found nothing.

I'm actually not that experienced with javascript and would appreciate any help

Thanks!

edit: Solved it as suggested by @Barmar using

var whiteList = temp.split('\n').map(s => s.trim());

Thank you everyone for your help!

9
  • What is the content of the list.txt ? Commented Feb 4, 2021 at 0:22
  • @justcodin In my tests it was: Mefa ADM_Sam Test I can only log with the last name, in this case being "Test" Commented Feb 4, 2021 at 0:26
  • Are they separated with new line or with space ? Commented Feb 4, 2021 at 0:27
  • It sounds like the lines are separated by \r\n, not \n. Commented Feb 4, 2021 at 0:28
  • @justcodin with new line Commented Feb 4, 2021 at 0:28

1 Answer 1

0

Try this :

const temp = fs.readFileSync('./list.txt', 'utf8');
const whiteList = temp.trim().split('\n');
const isLastItem = whiteList[whiteList.length - 1] === name;
Sign up to request clarification or add additional context in comments.

1 Comment

Trimming the whole file wasn't exactly the solution, but thanks for the insight!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.