1

I have a text file that is simply just:

a
b
c

1
2
3

I'm using fs from Node and I've read data using it before fine as long as it only reads data and separates it by a newline character.

I have:

var fs = require('fs')
var input = fs.readFileSync("./test.txt").toString().split("\n\n")
console.log(input)

This returns

[ 'a\r\nb\r\nc\r\n\r\n1\r\n2\r\n3' ]  // [ 'abc 123']

and not what I'd like, which is

[ 'a\r\nb\r\nc', '1\r\n2\r\n3' ]  // [ 'abc', '123' ]

Could someone explain to me the problem here? Also if you wouldn't mind explaining what the \r means that would be amazing! Thank you so much!

Phirip
  • 93
  • 1
  • 8
  • 1
    Does this answer your question? [How to split string by empty line in javascript](https://stackoverflow.com/questions/46551123/how-to-split-string-by-empty-line-in-javascript) – Matthew Moran Dec 04 '20 at 19:01
  • 1
    Maybe this link also can help you https://stackoverflow.com/questions/15433188/r-n-r-and-n-what-is-the-difference-between-them] – Haikel Dec 04 '20 at 19:07
  • 1
    Great links, they helped me come up with the answer! – Phirip Dec 04 '20 at 19:11

2 Answers2

1

you can try this

var fs = require('fs')
var input = fs.readFileSync("./text.txt",'utf-8').replace(/\r\n/g, " ").trim().split('  ')
console.log(input) //output [ 'a b c', '1 2 3' ]
0

So I just figured out a way to do it and I feel so :facepalm:

So since it was coming out as one whole string, I just furthered split it:

var fs = require('fs')
var input = fs.readFileSync("./test.txt").toString().split('\n\n')
var data = input[0].split("\r\n\r\n")
console.log(data[1])  // Correctly outputs ('1\n2\n3')

Also another solution that I just found out works as well!

var fs = require('fs')
var input = fs.readFileSync("./test.txt").toString().split('\r\n\r\n')
console.log(input[1])  // Also correctly outputs ('1\n2\n3')

Sorry about the post, but hope this helps someone else!

Phirip
  • 93
  • 1
  • 8