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
如何在數組中存儲值並將填充數組寫入文件? –
文本文件中有多少條記錄?百萬?十億? –