Append to file might not add new line

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-11-23

I wanted to print a stream of events as JSON. I did this by looping fs.appendFile 1000s of times in node.

When I inspected the output, all the JSON ended up on one single line of the output file, which was difficult to work with beause most unix tools default to assuming "one record per line".

The bit I was missing in my "append" code was adding a new line (with "\n") This confused me because the behavior here in node differs to the approach in shell, where the approximate equivalent does add a new line.

$ touch test.txt
$ echo "hello" >> test.txt
$ cat test.txt

hello

$ echo "hello" >> test.txt

$ cat test.txt
hello
hello

Lesson

Double-check if appending includes a newline in the platform of your choice.