SlinnShady
SlinnShady

Reputation: 515

Output and format a text file to html using node.js

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

Answers (1)

Nathan Chu
Nathan Chu

Reputation: 657

TL;DR: Use <pre> in HTML or .replace(/\n/g, '<br />') in Node.js


fs.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

Related Questions