gpt4 book ai didi

javascript - 使用 fs [node js] 将文本从文本文件转换为数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:23 25 4
gpt4 key购买 nike

我有一个txt文件包含:

{"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"select","nombre":4}

如何将文本文件的内容转换为数组,例如:

statement = [
{"date":"2013/06/26","statement":"insert","nombre":1}, {"date":"2013/06/26","statement":"insert","nombre":1}, {"date":"2013/06/26","statement":"select","nombre":4}, ];

我使用fs模块node js。谢谢

抱歉我会更详细地解释:

我有一个数组:

st = [
{"date":"2013/06/26","statement":"insert","nombre":1},
{"date":"2013/06/26","statement":"insert","nombre":5},
{"date":"2013/06/26","statement":"select","nombre":4},
];

如果我使用此代码:

var arr = new LINQ(st)
.OrderBy(function(x) {return x.nombre;})
.Select(function(x) {return x.statement;})
.ToArray();

我得到了我想要的结果。

insert select insert

但问题是我的数据位于文本文件中。任何建议,再次感谢。

最佳答案

没有理由不自己做文件解析器。这适用于任何大小的文件:

var fs = require('fs');

var fileStream = fs.createReadStream('file.txt');

var data = "";

fileStream.on('readable', function() {
//this functions reads chunks of data and emits newLine event when \n is found
data += fileStream.read();
while( data.indexOf('\n') >= 0 ){
fileStream.emit('newLine', data.substring(0,data.indexOf('\n')));
data = data.substring(data.indexOf('\n')+1);
}
});

fileStream.on('end', function() {
//this functions sends to newLine event the last chunk of data and tells it
//that the file has ended
fileStream.emit('newLine', data , true);
});

var statement = [];

fileStream.on('newLine',function(line_of_text, end_of_file){
//this is the code where you handle each line
// line_of_text = string which contains one line
// end_of_file = true if the end of file has been reached
statement.push( JSON.parse(line_of_text) );
if(end_of_file){
console.dir(statement);
//here you have your statement object ready
}
});

关于javascript - 使用 fs [node js] 将文本从文本文件转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com