0

I'm trying to convert a TSV file into JSON and write it to disk using text2json.

Input data

There is an empty line at the end

U+2B695 shī
U+2B699 pū
U+2B6DB zhī
U+2B6DE jué
U+2B6E2 níng
U+2B6F6 chì
U+2B6F8 tí

Test

I've this test running with ava

import fs from "fs";
import test from "ava";
import jsonfile from "jsonfile";
import dataminer from "../src/dataminer";

test("extractPronunciation()", t => {
  const filepath = "src/codepoint-ruby.tsv";

  const data = dataminer.convertToJson(filepath, { separator: " " });

  t.is(data > 0);
});

Code

And this method based on text2json:

import jsonfile from "jsonfile";
import text2json from "text2json";

export default {
  convertToJson: (filepath, options) => {
    const data = [];
    const parse = new text2json.Parser({ ...options, hasHeader: true });

    parse
      .text2json(filepath)
      .on("row", row => {
        data.push(row);
      })
      .on("end", () => {
        console.log("Done >>>>>");
        return data;
      });
  },
};

Question

I see not trace of the end event being triggered, and the convertToJson() return nothing so my test fail, am I missing something?

4

1 回答 1

2

在您的方法中,您data通过从流中异步读取来填充数组,而不是将整个文件放入内存并同步执行。(这就是为什么你必须使用on事件将数据推送到你的数组)。

这意味着,以您使用的相同方式

parse.text2json(filepath).on("row", row => {
      data.push(row);
});

您还需要使用end事件来记录最终结果

parse.text2json(filepath)
    .on("row", row => {
        data.push(row);
    })
    .on('end', () => {
        console.log(data)
    });
于 2017-03-27T17:55:45.893 回答