0

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()
  );

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.