2014-02-28 52 views
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'); 
} 

的代码使用splitthrough模块

如何存放值数组中,并编写填充阵列的文件吗?

== === ====== =================

更新: 这就是我想做的事,但它在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中做到这一点吗?

+1

那么问题是什么? – Pointy

+0

如何在数组中存储值并将填充数组写入文件? –

+0

文本文件中有多少条记录?百万?十亿? –

回答

1

除非你是在节点的新流API超舒适,使用event-stream模块来实现:

var fs = require('fs'); 
var es = require('event-stream'); 

function getIds(src, target, callback) { 
    var uniqueIDs = []; 
    es.pipeline(
    fs.createReadStream(src), 
    es.split(), 
    es.map(function (line, done) { 
     var id = line.split(',').shift(); 
     if (uniqueIDs.indexOf(id) > -1) return done(); 
     uniqueIDs.push(id); 
     done(null); 
    }), 
    es.wait(function (err, text) { 
     // Here we create our JSON — keep in mind that valid JSON starts 
     // as an object, not an array 
     var data = JSON.stringify({ ids: uniqueIDs}); 
     fs.writeFile(target, data, function (err) { 
     if ('function' == typeof callback) callback(err); 
     }); 
    }) 
); 
} 

getIds('./values.txt', './output.json'); 

不幸的是没有“简单”的方式来保持这个作为一个纯粹的流流动,所以你必须“等待”,直到数据完成过滤,然后转换为JSON字符串。希望有所帮助!

相关问题