0
我有一个文本文件,其中包含大量值,我希望使用node.js fs
模块将其转换为有意义的JSON。如何读取文件,存储数据然后编写它
我想存储数组中每行的第一个值,除非该值已经存在。
7000111,-1.31349,36.699959,1004,
7000111,-1.311739,36.698589,1005,
8002311,-1.262245,36.765884,2020,
8002311,-1.261135,36.767544,2021,
因此,对于这种情况下,我想写入文件:
[7000111, 8002311]
这里是我到目前为止所。它将[]
写入文件。
var fs = require('fs');
var through = require('through');
var split = require('split');
var shape_ids = [];
var source = fs.createReadStream('data/shapes.txt');
var target = fs.createWriteStream('./output3.txt');
var tr = through(write, end);
source
.pipe(split())
.pipe(tr)
// Function definitions
function write(line){
var line = line.toString();
var splitted = line.split(',');
// if it's not in array
if (shape_ids.indexOf(splitted[0]) > -1){
shape_ids.push(splitted[0]);
}
}
function end(){
shape_ids = JSON.stringify(shape_ids);
target.write(shape_ids);
console.log('data written');
}
如何存放值数组中,并编写填充阵列的文件吗?
== === ====== =================
更新: 这就是我想做的事,但它在Ruby中:
shape_ids = []
File.open("data/shapes.txt").readlines.each do |line|
data = line.split(',')
shape_id = data.first
if !shape_ids.include? shape_id
shape_ids.push(shape_id)
end
end
puts shape_ids # array of unique shape_ids
我可以在JavaScript中做到这一点吗?
那么问题是什么? – Pointy
如何在数组中存储值并将填充数组写入文件? –
文本文件中有多少条记录?百万?十亿? –