2

I'm writing a program that gives me random song names I've input into a text file. Here's the code I have so far:

var fs = require('fs'),
    path = require('path');

fs.readFile('names.txt', 'utf8', function(err, data) {
    var arr = data.toString().split('\n'),
        names = [];
    for (var i in arr) {
        if (arr[i].length !== 0) {
            names.push(arr[i].trim());
        }

    }


    console.log(names[1]);
});

I've noticed that whenever I put an odd number into the console.log() statement it returns the empty newline / whitespace. How can I fix this or remove it? Thanks for any help!

DevonAero
  • 75
  • 1
  • 6

3 Answers3

2

Your situation isn't entirely clear without full details, mainly the contents of the text file, but you probably meant to trim before the if.

Try like this:

for (var i in arr) {
        var trimmed = arr[i].trim();
        if (trimmed .length !== 0) {
            names.push(trimmed);
        }

}

Also, you shouldn't really for(.. in ..) in arrays (See here).

It's better if you use for(var i = 0; i < arr.length; i++) (you can keep the rest exactly as it is)

Community
  • 1
  • 1
Amit
  • 45,440
  • 9
  • 78
  • 110
1

Alternatively:

var names = data.toString().split('\n').map(function(line){
    return line.trim();
}).filter(Boolean);
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Looks good, it's amazing how many different ways you can solves problems in programming. Thanks so much! – DevonAero Jul 26 '15 at 15:27
0

I tried this below piece of code and it worked!

const fs = require('fs');
let names = []
try{
    //Getting the entire file into a constant
    const data = fs.readFileSync('./sidd.txt','utf8')
    //Removing the extra empty new lines if exist after end of file text
    let newData = data.trim()
    //Imagining that the different song names are written with new lines
    names = newData.split('\n')
    
    console.log(names[0])
}
catch(err)
{
    console.log(err)
}

Note: This code will work if the song names are delimited with new line