Home > database >  how to sort data in the file from file System read method in JavaScript?
how to sort data in the file from file System read method in JavaScript?

Time:02-23

How to sort the data obtained from read filesystem method in javascript

fs.readFile('node1.txt',function(err,data){   

          if(err){

             return console.log(err)    

           }

           data.toString().toLocaleUpperCase.sort(function (first, second){

                if(first<second){

                    return -1

                }else if(first>second){

                       return 1

                }else{

                   return 0
                }
         })
}

** TypeError: sort is not a function **

CodePudding user response:

Basically what your code is trying to do here with the line data.toString().toLocaleUpperCase.sort is :

Taking the data, transforming it into a string with the toString() method and the sorting the string.

The problem here is that you're trying to sort a string and in Javascript, String has not sort method.

What you should do is transforming your string into an array with the split method (documentation here)

For example if you want to sort the file into words :

data.toString().split(' ').sort(function (first, second){
   if(first.toLocaleUpperCase() < second.toLocaleUpperCase()){
      return -1
   } else if(first.toLocaleUpperCase() > second.toLocaleUpperCase()){
      return 1
   } else{
      return 0
   }
})

CodePudding user response:

toLocalUpperCase() is a function not a property.

Try data.toString().toLocaleUpperCase().sort(...)

Note the extra brackets

  • Related