3

I am reading a file line by line with nodejs 'readline'. I am reading a .csv file line by line and converting it to JSON. I start with writing '{' then each line is parsed, formatted, and terminated with ','. I want to do something different with the last line than the preceding lines ie. terminate with a '}' instead of a ','. How do I detect that the current line is the last line.

    var readline = require("readline");
    var fs = require("fs");

    var read_in = readline.createInterface({
        input: fs.createReadStream(file),
        crlfDelay: Infinity
    });

    var write_out = fs.createWriteStream("intermediate.json")

    write_out.write("{");

    read_in.on("line", function (line) {
        var a = line.split(",");
        var b = "\"" + a[0].trim() + "\" : \"" + a[1] + "\",\r\n"
        write_out.write(b);
    })
    read_in.on("close", function () {
        write_out.write("}"); // leaves an incorrectly formatted JSON file
    })
MikeB
  • 788
  • 1
  • 9
  • 27

1 Answers1

0

A fun way to do this using a csv, but it should work with any type of doc.

Document Contents

one,apple
two,banana
three,orange

Code

// Load document
const originalStream = fs.readFileSync(`my_document.csv`);

// Convert document to hex
const hexStream = new Buffer.from(streambase).toString('hex')
// Output 
// 6f6e652c6170706c650a74776f2c62616e616e610a74687265652c6f72616e6765
// New lines are separated by 0a so we can assume thats the start of a new line

// Retrieve last line in hex format
const lastLineHex = hexStream.split("0a").splice(-1)[0]
// Output
// 74687265652c6f72616e6765

const convertLastLineBackToUtf = new Buffer.from(lastLineHex, 'hex').toString();
// Output
// three,orange

To check if they are on the last line you could compare it with this final output.

Troy
  • 138
  • 1
  • 2
  • 10