2017-08-16 13 views
3

非常に大きな位置履歴ファイルを読み込んでデータを抽出し、JSONデータとしてファイルに書き込む必要があります。どうやってやるの。 次のコードは出力を生成しません。 編集:これが私の問題私の解決策であるのFileOutputStreamNodejs JSONファイルを解析してJSON配列としてファイルに書き込む

const fs = require('fs') 
var JSONStream = require('JSONStream'); 
var es = require('event-stream'); 
const filePath = './location-history.json' 
const fileOutputPath = './transform-location-history.json' 

fileStream = fs.createReadStream(filePath); 
fileOutputStream = fs.createWriteStream(fileOutputPath) 

const transformer = (data) => { 
    const location = { 
     latitude: data.latitudeE7/10000000, 
     longitude: data.longitudeE7/10000000 
    } 
    return JSON.stringify(location); 
} 

fileStream 
.pipe(JSONStream.parse('locations.*')) 
.pipe(es.through(transformer)) 
.pipe(fileOutputStream) 
+0

(https://stackoverflow.com/questions/11874096/parse-large-json-file-in-nodejs)[Nodejsに大きなJSONファイルを解析] – Veve

+0

の可能性のある重複し、それがない理由出力ストリームに書き込みますか? – user3405462

+0

すべてがうまく見えます。あなたはデータ変数 –

答えて

1

にパイプているため が、私は、ファイル内の文字列を出力することを期待。 JSONStreamは入力ファイルを解析し、JSONオブジェクトを吐き出します。 es.through(トランスフォーマ)はJSONオブジェクトを取得し、文字列としてファイルに書き込みます。 ES6でファイル出力ファイルをインポート可能にするには、 'export default locationHistory'が追加されます。 https://gist.github.com/tuncatunc/35e5449905159928e718d82c06bc66da

const fs = require('fs') 
const JSONStream = require('JSONStream'); 
var es = require('event-stream'); 
const filePath = './location-history.json' 
const fileOutputPath = './transform-location-history.js' 

const fileStream = fs.createReadStream(filePath); 
const fileOutputStream = fs.createWriteStream(fileOutputPath) 

let index = 0; 
const transformer = (data) => { 
    const location = { 
     latitude: data.latitudeE7/10000000, 
     longitude: data.longitudeE7/10000000 
    }; 
    let result = JSON.stringify(location) + ','; 
    if (index === 0) { 
    result = 'const locationHistory = [' + result 
    } 
    index++; 
    if (index < 100) 
    fileOutputStream.write(result); 
} 

const end =() => { 
    const finish = ']; export default locationHistory\n' 
    fileOutputStream.write(finish,() => { 
    fileOutputStream.close() 
    }) 
    console.log(`${index} objects are written to file`) 
} 

fileStream 
.pipe(JSONStream.parse('locations.*')) 
.pipe(es.through(transformer, end)) 
関連する問題