首页 > 解决方案 > 如何编写大小未知的 tar 流条目?

问题描述

这是我正在尝试做的事情的要点:

import * as Path from 'path'
import {exportTableDataToFile} from '../struct'
import * as Tar from 'tar-stream'
import * as Zlib from 'zlib'
import * as FileSys from 'fs'

async function execute(opts, args) {
    const pack = Tar.pack()

    pack.pipe(Zlib.createGzip({level: Zlib.constants.Z_BEST_COMPRESSION})).pipe(FileSys.createWriteStream(opts.file))

    const tblDataFile = Path.join(db.name, `${tblName}.csv`)
    const dataStream = pack.entry({name: tblDataFile}, err => {
        if(err) throw err;
    })
    await exportTableDataToFile(conn, db.name, tblName, dataStream)
}

在哪里将 CSV逐行exportTableDataToFile写入。dataStream

由于我是从一些数据库记录中即时生成 CSV,所以我不知道它会有多大。

如果可以的话,我也不想将整个 CSV 缓冲到内存中。

以上是抛出“尺寸不匹配”,因为我没有指定尺寸pack.entry(...)

有什么方法可以.tar.gz在不知道大小的情况下流式传输到 Node.js 中的 a 吗?

标签: node.jstarzlib

解决方案


如果您只想从未知大小的数据库创建 CSV,而不是使用某些模块,您可以执行以下相同操作:

const fs = require("fs");

const csvFile = fs.createWriteStream("db.csv");
//column headers of your csv, remove if not needed
csvFile.write("column1, column2, column3, column4");

while(true){
  const result=db.find(table);//db call -> replace it with your db fetch call
  //Here I am expecting column1Value ... to be the field in my DB
  for(const elem of result){
    csvFile.write(`${elem.column1Value}, ${elem.column2Value}, ${elem.column3Value}, ${elem.column4Value}`);
  }
  if(!result.length){
    break
  }
//Need to handle pagination

}

您可以根据您的语法替换 DB 调用。


推荐阅读