K
K
kr_ilya2020-04-19 17:45:56
JavaScript
kr_ilya, 2020-04-19 17:45:56

Is there a universal way to put the lines of a text file into an array?

There is a text file

one
two
three
chetire
five
etc

It can be changed in a text editor on windows and uploaded to the ubuntu server via ssh. In addition, lines can be added to it by a script (nodejs).
fs.appendFileSync(Users, `${os.EOL}${text}`);//Users - файл, text - новая строка os.EOL - см.ниже

Why am I ..
The line break character in windows \r\n, but in ubuntu \n. Because of this, I'm having trouble creating an array from the lines of a file.
Lines up to chetire have been added to windows. Everything below is a script on the server
let fileContent = fs.readFileSync(Users, "utf8");  //Users - файл
var sList = fileContent.split(os.EOL); //os.EOL - возвращает символ переноса строки, характерный для текущей операционной системы. см. выше
console.log(sList);
//sList будет в данном случае будет содержать
    [
      'one\r',
      'two\r',
      'three\r',
      'chetire',
      'five',
      'etc'
    ]

//При этом
console.log(sList[0]); 
//Вернет в консоль one без \r

I tried cleaning \rwith but it didn't work. The problem is that sList.indexOf('one'); will return -1 due to \r, although in fact it should return 0 Of course, it would be possible to use the transfer when adding lines in the script and not take a steam bath, but I think that this is only a superficial fix, and if, for example, you need to manually edit the file on Linux, there will be a similar problem. How can the script be universalized so that it works for files from both Windows and Linux? item.replace(/\r?\n/g, "")
\r\n

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2020-04-19
@kr_ilya

fileContent.split(/\r?\n/)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question