0

I'm trying to create a text file with one string (called 'summary') as the only content. summary consists of many different lines, so I use '\n' quite a lot. However, the text file that gets created writes the string in a single line. Why do the '\n's get ignored?

This is the function I'm using:

 function writeToTxt(summary){
  var fileType = "text/txt";
  var fileName = Date.now()+".txt";

  var blob = new Blob([summary], { type: fileType });

  var a = document.createElement('a');
  a.download = fileName;
  a.href = URL.createObjectURL(blob);
  a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
  a.style.display = "none";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500);
}

Thanks!

3
  • 4
    \n is a line break on *nix, but not on Windows. If you're looking at the file on Windows, that's probably why you're not seeing line breaks. For Windows it's \r\n. Commented Jan 2, 2018 at 11:23
  • What makes you think there are no line breaks in the file? How did you open it? Commented Jan 2, 2018 at 11:45
  • And, of course, you need to provide \n as part of a JavaScript string literal. Anything else (e.g. reading it from a text file) will not get it parsed. Commented Jan 2, 2018 at 11:49

1 Answer 1

2

Your file creation code is fine, but \n isn't a line break on Windows (it is on *nix). If you're looking at the file on Windows, that's probably why you're not seeing line breaks. For Windows it's \r\n.

Your code works just fine for me on Windows if I use \r\n, and on *nix if I use just \n. (Many *nix tools will also handle \r\n line endings, what with there being so many Windows-like text files around...)

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

2 Comments

Any decent editor should show \n as linebreaks on Windows as well.
@Bergi: Yes. But people often seem to use Notepad instead. :-)

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.