0

I have a string that when I grab to print to a text file , It prints the string without new line after each message even though I explicitly put it in '\n' in the string. So how I'm putting together the string is as follows :

I send the message to server then I emit it back to all clients, when the data reaches the client, it grabs the text.Content and prints to a div.

var stringMessage= 'session\n' + '';

socket.on('output', function(data){
        if(data.length){
          //loop through all data.
              for(var x=0; x<data.length; x=x+1){
                if(data[x].sessionId == sessionId){
                  var message = document.createElement('div');
                  message.setAttribute('class','chat-message');
                  message.setAttribute('id','chat-message');
                  message.textContent = data[x].name + ': ' + data[x].message;
                  var chat_message = message.textContent;
                  stringMessage = stringMessage +'\n'+ chat_message + '\n';

                  //Append
                  messages.insertBefore(message, messages.firstChild);
                  messages.appendChild(message);
                  messages.scrollTop = messages.scrollHeight;//(message, messages.firstChild);
                }
              }
        }
});

Then I have a function to grab the string stringMessage that will have all the messages in the string.

function grabChat(){
  var hiddenElement = document.createElement('a');

  hiddenElement.href = 'data:attachment/text,' + encodeURI(stringMessage);
  hiddenElement.target = '_blank';
  hiddenElement.download = sessionId+'.txt';
  hiddenElement.click();
}

so If I have messages like so: "Andrew : Hello" "Andrew : Goodbye" and then I print the function it prints like so : "sessionIdAndrew : HelloAndrew : Goodbye"

how do I create a new line between all messages? I tried '\n' as you can see in the code

1 Answer 1

2

That's a HTML output. Replace \n with <br />:

var stringMessage= 'session<br />\n' + '';

Else using CSS, you need to set the element's style to be:

white-space: pre-wrap;
Sign up to request clarification or add additional context in comments.

3 Comments

hmmm it seems that when i open the txt file with Notepad its on one line but when I open it with sublime text 2 they are on different lines
@AndrewONeill There's a difference between how OS renders \n and \r\n.
Windows would use \r\n (Carriage Return / Line Feed) while Unix Based (Linux, Mac) use just \n (Line Feed). So when you open it in Windows or save there, and you open it in Linux, you will see two lines. Hope you understood.

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.