【问题标题】:Nodejs Parse Json file transform the input and write to file as JSON arrayNodejs Parse Json 文件将输入转换为 JSON 数组写入文件
【发布时间】:2018-01-24 12:45:39
【问题描述】:

我需要读取一个非常大的位置历史记录文件并提取一些数据并将其作为 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)

【问题讨论】:

标签: javascript json node.js jsonstream


【解决方案1】:

这是我的问题的解决方案。 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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-13
    • 2017-10-05
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多