Javascript Nodejs解析Json文件将输入和写入文件转换为Json数组
我需要读取一个非常大的位置历史文件,提取一些数据并将其作为JSON数据写入文件。我该怎么做呢。 以下代码不生成任何输出。 编辑: 我希望在文件中输出字符串,因为它通过管道传输到fileOutputStreamJavascript Nodejs解析Json文件将输入和写入文件转换为Json数组,javascript,json,node.js,jsonstream,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' con
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对象。通过(transformer)获取JSON对象并将其作为字符串写入文件。为了使文件输出文件在ES6中可导入,添加了“导出默认位置历史记录”。
const fs=require('fs'))
const JSONStream=require('JSONStream');
var es=需要(‘事件流’);
const filePath='./location history.json'
const fileOutputPath='。/transform location history.js'
const fileStream=fs.createReadStream(文件路径);
const fileOutputStream=fs.createWriteStream(fileOutputPath)
设指数=0;
常量转换器=(数据)=>{
常数位置={
纬度:data.latitudeE7/10000000,
经度:data.longitudeE7/10000000
};
让result=JSON.stringify(location)+',';
如果(索引==0){
结果='const locationHistory=['+结果
}
索引++;
如果(指数<100)
fileOutputStream.write(结果);
}
常量结束=()=>{
const finish='];导出默认位置历史记录\n
fileOutputStream.write(完成,()=>{
fileOutputStream.close()
})
log(`${index}对象被写入文件`)
}
文件流
.pipe(JSONStream.parse('locations.*'))
.管道(穿过(变压器,端部))
为什么它不写入输出流的原因可能重复?一切看起来都很好。请说明从何处将值写入数据变量样本输入。原始文件的点数超过200K。
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))