如何在Gridsome中使用本地数据源的JSON Stream创建静态页面

问题描述

我有一个大型 JSON 文件,我想将其用作 Gridsome 的本地数据源以生成静态页面

我想流式传输数据而不是将其全部加载到内存中。

gridsome.server.js 中的类似内容

module.exports = function (api) {
  api.loadSource(async (actions) => {
    const collection = actions.addCollection({
      typeName: 'Posts',})
    const StreamArray = require('stream-json/streamers/StreamArray')
    const fs = require('fs')

    const jsonStream = StreamArray.withParser()

    //internal Node readable stream option,pipe to stream-json to convert it for us
    fs.createReadStream('./src/data/posts.json').pipe(jsonStream.input)

    //You'll get json objects here
    //Key is the array-index here
    jsonStream.on('data',({ key,value }) => {
      collection.addNode(value)
    })

    jsonStream.on('end',value }) => {
      console.log('All Done')
    })
  })
}

这种方法有缺陷吗?我想知道这是否可能因为它的异步性质而不起作用。有人试过类似的吗?

解决方法

这种方法有什么缺陷吗?

不 - 这应该有效。