Does something similar to Java\'s System.getProperty(\"line.separator\"); exist in JavaScript?
Edit: I am using the non-browser JavaScript environment
Not defined by the standard, no. Section 7.3 defines line terminators for the source code of a JavaScript program (there are four), but nothing related to the platform's definition of a line terminator for text.
If you're talking about non-browser environments (shell scripts, server-based JavaScript, etc.), I'd look at the documentation for the environment in which you're running (NodeJS, Rhino, etc.), which will hopefully have that kind of environmental info for you. (In Rhino, of course, you can just use Java's.)
If you're talking about browser-based environments, by and large, \n is used, but it's that "by and large" that can bite you. :-) Some browsers will even convert line endings, such as in a textarea, before JavaScript even sees them. For instance, the raw version of this page has no carriage returns in it at all. And yet, if you run that page in Internet Explorer, note that it says it found \r characters in the text area's value. Not so Chrome or Firefox (even when running on Windows), but Opera adds them too (even when running on *nix). So on browsers, I tend to "normalize" line endings when accessing multi-line field values, via str = str.replace(/(?:\r\n|\r)+/g, "\n");, just in case. (That assumes that \r, both on its own and when followed by \n, should be a line break; older Macs used \r on its own.)
Continuing with the browser side of things, since different browsers do different things even on the same OS, is there any way to know what they use? Why, yes there is, you can find out with a sneaky trick:
function getLineBreakSequence() {
var div, ta, text;
div = document.createElement("div");
div.innerHTML = "";
ta = div.firstChild;
text = ta.value;
return text.indexOf("\r") >= 0 ? "\r\n" : "\n";
}
This works because the browsers that use \r\n convert the \n on-the-fly when parsing the HTML string. Here's a live running copy you can try for yourself with your favorite browser(s).
Update: Ah, you're using NodeJS. Sadly, like you, I don't see anything at all about this in the NodeJS docs. NodeJS is very closely tied to C/C++, and in C/C++, you use \n for linebreak regardless of the OS — on streams opened in text mode it gets converted to the OS-specific version on the fly (both read and write). But I don't see any support for text-mode file streams in NodeJS. The fs.open function doesn't document the b flag from fopen (which is otherwise where it got that flags syntax), and if you look at the source, it sets _fmode to _O_BINARY on MinGW. All of which leads me to suspect that files are only ever in binary mode. console.log's implementation uses \n for newline, for what that's worth.