简体   繁体   English

在 JavaScript 中读取文件并用空行分隔数据

[英]Reading a file and separating data by blank lines in JavaScript

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.我正在使用来自 Node 的 fs 并且我之前已经使用它读取数据,只要它只读取数据并用换行符分隔它。

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!此外,如果您不介意解释 \r 的含义,那就太棒了! Thank you so much!太感谢了!

So I just figured out a way to do it and I feel so:facepalm:所以我只是想出了一个方法来做到这一点,我觉得这样: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!抱歉这篇文章,但希望这对其他人有帮助!

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' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM