Charles Spencer
Charles Spencer

Reputation: 657

In NodeJS, how do you print lines to a file without manually adding the new line character?

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?

Upvotes: 0

Views: 913

Answers (2)

Christian Benseler
Christian Benseler

Reputation: 8075

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')

Upvotes: 1

Matt Mokary
Matt Mokary

Reputation: 727

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.

Upvotes: 1

Related Questions