3

我需要读取一个非常大的位置历史文件并提取一些数据并作为 JSON 数据写入文件。我怎样才能做到这一点。以下代码不会生成任何输出。编辑:我希望在文件中输出字符串,因为它通过管道传输到 fileOutputStream

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)
4

1 回答 1

2

这是我的解决方案我的问题。JSONStream 解析输入文件并吐出 JSON 对象。es.through(transformer) 获取 JSON 对象并将其作为字符串写入文件。为了使文件输出文件在 ES6 中可导入,添加了“导出默认 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))
于 2017-08-17T04:58:46.040 回答