Reputation: 515
I am looking to output the contents of a text file to a webpage using node.js. I have managed to get the text from the file and have been able to use it together with some basic HTML to render a page but the text has lost all its formatting and is rendered as one long string:
i.e. the contact.txt file has the following in it:
Peter
Robert
Bob
but when I use fs.readFile
I get the following on my page:
Peter Robert Bob
Does anyone know how to preserve the line breaks in the original text file? The code I am using follows
fs.readFile('contact.txt', (error, txtString) => {
if(error) throw err;
console.log(txtString.toString());
res.write(
'<div id="content">'+ txtString.toString()
);
Upvotes: 0
Views: 2934
Reputation: 657
<pre>
in HTML or .replace(/\n/g, '<br />')
in Node.js<pre>
in HTML keeps ALL formatting.replace(/\n/g, '<br />')
in Node.js ONLY fixes newlinesfs.readFile
returns the following correctly:
Peter
Robert
Bob
But, look at this:
<div>
Peter
Robert
Bob
</div>
Notice that the output is Peter Robert Bob
.
To fix this, you have a few options. The first is <pre>
tags:
<div><pre>
Peter
Robert
Bob
</pre></div>
Using this solution, your code would be:
fs.readFile('contact.txt', (error, txtString) => {
if(error) throw err;
console.log(txtString.toString());
res.write(
'<div id="content"><pre>'+ txtString.toString()+'</pre>'
);
The next would be replacing newlines with <br />
(the HTML newline) on the server. With this approach, your code would look like:
fs.readFile('contact.txt', (error, txtString) => {
if(error) throw err;
console.log(txtString.toString());
res.write(
'<div id="content"><pre>'+ txtString.toString().replace(/\n/g, '<br />')+'</pre>'
);
With that, the response looks like:
<div> Peter<br /> Robert<br /> Bob<br /> </div>
Upvotes: 1