javascript - Nodejs Parse Json 文件转换输入并作为 JSON 数组写入文件

标签 javascript json node.js jsonstream

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

最佳答案

这是我的解决方案。 JSONStream 解析输入文件并吐出 JSON 对象。 es.through(transformer) 获取 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))

关于javascript - Nodejs Parse Json 文件转换输入并作为 JSON 数组写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45712457/

相关文章:

javascript - 如何在 express.js 应用程序启动之前加载异步数据库 url 并启动数据库连接?

javascript 未在 HTML 文件中加载 - NodeJS + ExpressJS

javascript - 使用node.js和mysql进行简单的注册/登录

javascript - 如何使用 ref 回调将对象数组从一个组件传递到 React js 中的另一个组件

javascript - Angular 4 动画正在 init 组件上执行

objective-c - 在 iOS 中保存 JSON 对象

java - 从流中删除开头和结尾字符

javascript - 如何根据jsp中的条件禁用按钮?

javascript - 获取嵌套元素值

javascript - 在 d3 中堆叠一个矩阵而不重新映射到 json