Reputation: 93
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!
Upvotes: 1
Views: 1017
Reputation: 102
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' ]
Upvotes: 1
Reputation: 93
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!
Upvotes: 0