Javascript 使用fs[node js]将文本文件转换为数组
我有一个txt文件包含: {“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1} {“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1} {“日期”:“2013/06/26”,“声明”:“选择”,“名称”:4} 如何将文本文件的内容转换为数组,例如: 语句=[Javascript 使用fs[node js]将文本文件转换为数组,javascript,node.js,Javascript,Node.js,我有一个txt文件包含: {“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1} {“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1} {“日期”:“2013/06/26”,“声明”:“选择”,“名称”:4} 如何将文本文件的内容转换为数组,例如: 语句=[ {“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1}, {“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1}, {“日期”:“2013/06/26”,“声明”:“
{“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1}, {“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1}, {“日期”:“2013/06/26”,“声明”:“选择”,“名称”:4},]强> 我使用fs模块节点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();
我得到了我想要的结果
插入选择插入
但问题是我的数据在一个文本文件中。
任何建议,再次感谢
fs.readFileSync("myfile.txt").toString().split(/[\r\n]/)
这会将您的每一行作为字符串
然后,您可以使用下划线或自己的for循环将JSON.parse(“您的JSON字符串”)
方法应用于数组的每个元素
这会将您的每一行作为字符串
然后,您可以使用下划线或自己的for循环将
JSON.parse(“您的JSON字符串”)
方法应用于数组的每个元素。如果它是一个小文件,您可能会遇到如下情况:
// specifying the encoding means you don't have to do `.toString()`
var arrayOfThings = fs.readFileSync("./file", "utf8").trim().split(/[\r\n]+/g).map(function(line) {
// this try/catch will make it so we just return null
// for any lines that don't parse successfully, instead
// of throwing an error.
try {
return JSON.parse(line);
} catch (e) {
return null;
}
// this .filter() removes anything that didn't parse correctly
}).filter(function(object) {
return !!object;
});
如果它更大,您可能需要考虑使用NPM上的任意一个模块逐行读取它来从流中消耗行。 想看看如何使用streams吗?让我们看看如何使用流。这不是一个实际的例子,但无论如何都很有趣
var stream = require("stream"),
fs = require("fs");
var LineReader = function LineReader(options) {
options = options || {};
options.objectMode = true;
stream.Transform.call(this, options);
this._buffer = "";
};
LineReader.prototype = Object.create(stream.Transform.prototype, {constructor: {value: LineReader}});
LineReader.prototype._transform = function _transform(input, encoding, done) {
if (Buffer.isBuffer(input)) {
input = input.toString("utf8");
}
this._buffer += input;
var lines = this._buffer.split(/[\r\n]+/);
this._buffer = lines.pop();
for (var i=0;i<lines.length;++i) {
this.push(lines[i]);
}
return done();
};
LineReader.prototype._flush = function _flush(done) {
if (this._buffer.length) {
this.push(this._buffer);
}
return done();
};
var JSONParser = function JSONParser(options) {
options = options || {};
options.objectMode = true;
stream.Transform.call(this, options);
};
JSONParser.prototype = Object.create(stream.Transform.prototype, {constructor: {value: JSONParser}});
JSONParser.prototype._transform = function _transform(input, encoding, done) {
try {
input = JSON.parse(input);
} catch (e) {
return done(e);
}
this.push(input);
return done();
};
var Collector = function Collector(options) {
options = options || {};
options.objectMode = true;
stream.Transform.call(this, options);
this._entries = [];
};
Collector.prototype = Object.create(stream.Transform.prototype, {constructor: {value: Collector}});
Collector.prototype._transform = function _transform(input, encoding, done) {
this._entries.push(input);
return done();
};
Collector.prototype._flush = function _flush(done) {
this.push(this._entries);
return done();
};
fs.createReadStream("./file").pipe(new LineReader()).pipe(new JSONParser()).pipe(new Collector()).on("readable", function() {
var results = this.read();
console.log(results);
});
var stream=require(“stream”),
fs=要求(“fs”);
var LineReader=函数LineReader(选项){
选项=选项| |{};
options.objectMode=true;
stream.Transform.call(此选项);
这个;
};
LineReader.prototype=Object.create(stream.Transform.prototype,{constructor:{value:LineReader}});
LineReader.prototype._transform=函数_transform(输入、编码、完成){
if(Buffer.isBuffer(输入)){
输入=输入.toString(“utf8”);
}
这个._buffer+=输入;
var lines=this.\u buffer.split(/[\r\n]+/);
这个._buffer=lines.pop();
对于(var i=0;i,如果它是一个小文件,您可能会得到如下结果:
// specifying the encoding means you don't have to do `.toString()`
var arrayOfThings = fs.readFileSync("./file", "utf8").trim().split(/[\r\n]+/g).map(function(line) {
// this try/catch will make it so we just return null
// for any lines that don't parse successfully, instead
// of throwing an error.
try {
return JSON.parse(line);
} catch (e) {
return null;
}
// this .filter() removes anything that didn't parse correctly
}).filter(function(object) {
return !!object;
});
如果它更大,您可能需要考虑使用NPM上的任意一个模块逐行读取它来从流中消耗行。
想看看如何使用流吗?让我们看看如何使用流。这不是一个实际的例子,但无论如何都很有趣
var stream = require("stream"),
fs = require("fs");
var LineReader = function LineReader(options) {
options = options || {};
options.objectMode = true;
stream.Transform.call(this, options);
this._buffer = "";
};
LineReader.prototype = Object.create(stream.Transform.prototype, {constructor: {value: LineReader}});
LineReader.prototype._transform = function _transform(input, encoding, done) {
if (Buffer.isBuffer(input)) {
input = input.toString("utf8");
}
this._buffer += input;
var lines = this._buffer.split(/[\r\n]+/);
this._buffer = lines.pop();
for (var i=0;i<lines.length;++i) {
this.push(lines[i]);
}
return done();
};
LineReader.prototype._flush = function _flush(done) {
if (this._buffer.length) {
this.push(this._buffer);
}
return done();
};
var JSONParser = function JSONParser(options) {
options = options || {};
options.objectMode = true;
stream.Transform.call(this, options);
};
JSONParser.prototype = Object.create(stream.Transform.prototype, {constructor: {value: JSONParser}});
JSONParser.prototype._transform = function _transform(input, encoding, done) {
try {
input = JSON.parse(input);
} catch (e) {
return done(e);
}
this.push(input);
return done();
};
var Collector = function Collector(options) {
options = options || {};
options.objectMode = true;
stream.Transform.call(this, options);
this._entries = [];
};
Collector.prototype = Object.create(stream.Transform.prototype, {constructor: {value: Collector}});
Collector.prototype._transform = function _transform(input, encoding, done) {
this._entries.push(input);
return done();
};
Collector.prototype._flush = function _flush(done) {
this.push(this._entries);
return done();
};
fs.createReadStream("./file").pipe(new LineReader()).pipe(new JSONParser()).pipe(new Collector()).on("readable", function() {
var results = this.read();
console.log(results);
});
var stream=require(“stream”),
fs=要求(“fs”);
var LineReader=函数LineReader(选项){
选项=选项| |{};
options.objectMode=true;
stream.Transform.call(此选项);
这个;
};
LineReader.prototype=Object.create(stream.Transform.prototype,{constructor:{value:LineReader}});
LineReader.prototype._transform=函数_transform(输入、编码、完成){
if(Buffer.isBuffer(输入)){
输入=输入.toString(“utf8”);
}
这个._buffer+=输入;
var lines=this.\u buffer.split(/[\r\n]+/);
这个._buffer=lines.pop();
对于(var i=0;i,没有理由不自己进行文件解析器。这将适用于任何大小的文件:
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
}
});
没有理由不自己进行文件解析。这将适用于任何大小的文件:
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
}
});
var arr=fs.readFileSync('mytxtfile','utf-8').split('\n')
我认为这是从文本文件创建数组的最简单方法。var arr=fs.readFileSync('mytxtfile','utf-8')。split('\n')
我认为这是从文本文件创建数组的最简单方法什么数据在什么文本文件中?你在这里很模糊。我的文件内容:{“日期”:“2013/06/26”,“语句”:“插入”,“nombre”:1}{“日期”:“2013/06/26”,“语句”:“插入”,“nombre”:1}…你的问题现在完全不同了,但我认为你的答案可以告诉你如何从文本文件将数据放入数组。是的..这就是我们都解释过的..如何基于该文件创建st
数组什么数据在什么文本文件中?你在这里有点含糊不清。我的文件内容:{“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1}{“日期”:“2013/06/26”,“声明”:“插入”,“名称”:1}”..你的问题现在完全不同了,但我认为你的答案可以告诉你如何从文本文件将数据放入数组。是的..这就是我们都解释过的..如何基于该文件创建st
数组真的吗?-1?描述我的答案有什么问题会很好。很好的流示例…但来自pr如果你只是想要一个文件读取器,最好使用事件。它运行得更快。但是streams解决方案有利于代码的重用。真的吗?-1?描述一下我的答案有什么问题就好了。很好的流示例…但是从实践来看,如果你只是想要一个文件读取器,最好使用事件。它运行得更快。但是streams解决方案是go代码重用的od。就是这样。非常感谢。YW..但是Deoxa指出,将JSON解析器放在try{}catch{}中很好所以它不会因为格式错误的JSONHi再次崩溃,在我的文本文件中,我的末尾有一个空行,所以我总是会遇到这样的错误:输入的意外结尾有没有删除最后一个空文件的建议,谢谢。我发现了它,我添加了以下条件:if(line\u of_text!=''){statement.push(JSON.parse(line\u of_text));}
如前所述……您应该只编写try{statement.push(JSON.parse(line_of_text))}catch(e){}
来避免我在parsing出现的所有错误就是这样。非常感谢您。YW..但是Deoxa指出,将JSON解析器放在try{}catch{}中是件好事所以它不会因为格式不好的JSONHi再次崩溃,在我的文本文件中,我的结尾有一个空行,所以我总是会遇到这样的错误:输入的意外结束有没有删除最后一个空文件的建议,谢谢