0

I'm trying to figure out how to simply write a string representing a line to a file, where whatever function I call automatically appends a newline character.

I've tried using the default NodeJS file system library for this but I can't get this to work in any way without manually appending '\n' to the string.

Here's the code I tried:

const fs = require('fs');
const writer = fs.createWriteStream('test.out.txt', { flags: 'w' })

writer.write('line 1')
writer.write('line 2');
writer.write('line 3');
writer.end('end');

However, the output file test.out.txt contains the following line with no newline characters:

line 1line 2line 3end

I would like it to look like this:

line 1
line 2
line 3
end

Note that I'm not trying to log messages, and I'm not trying to redirect standard output.

Is there any way to print it this way with the new line characters automatically added?

Charles Spencer
  • 626
  • 1
  • 6
  • 17

2 Answers2

1

Manually appending the \n isn't so bad.

You could write a wrapper function to avoid having to put the + '\n' everywhere:

const os = require('os');

let writeln = function (writeStream, str) {
    writeStream.write(str + os.EOL);
}

writeln(writer, 'line 1');
writeln(writer, 'line 2');
writeln(writer, 'line 3');
writeln(writer, 'end');

From what I can tell by a cursory look over the fs.WriteStream docs, there's no native writeln function, or anything similar.

Matt Mokary
  • 717
  • 6
  • 13
  • 1
    but it is better to use `os.EOL` instead of hard-coded '\n' – RidgeA Mar 12 '18 at 19:20
  • So I should also add that my goal is to use NodeJS to make several command line programs, so if I add code myself to do this, I'd have to make a library they could all share. Is there already a library out there? – Charles Spencer Mar 12 '18 at 19:21
  • 1
    Thanks @RidgeA, edited. There could very well be a library out there that would add these couple lines for you, but it could also do things you don't want and you may have to fight with it to narrow it down to your specific purpose. This is a case in which it probably makes sense to create a shared utility that you maintain, and that does exactly what you need it to. – Matt Mokary Mar 12 '18 at 19:25
1

As mentioned in the comments, you can write a function to add a text as a line

const writeLine = (writerObject, text) => {
  writerObject.write(`${text}\n`)
}
writeLine(writer, 'line 1')
writeLine(writer, 'line 2')
writeLine(writer, 'line 3')

Or you can also use a clojure to create a wrapper object that keeps the 'writer' instead of passing it every time

const customWriter = writerObject => {
  return text => writerObject.write(`${text}\n`)
}

const yourWriterWithBreakLine = customWriter(writer)
yourWriterWithBreakLine('line 1')
yourWriterWithBreakLine('line 2')
yourWriterWithBreakLine('line 3')
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71