Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the platform specific newline character in JavaScript?

Years ago, I wrote the following function for one of my Firefox add-ons which helps me obtain a platform specific newline character:

GetNewLine: function()
{
    var platform = navigator.platform.toLowerCase();

    if(platform.indexOf('win') != -1) // Windows
        return "\r\n";
    else if(platform.indexOf('mac') != -1) // Mac
        return "\r";
    else // *nix
        return "\n";
}

This seems to work OK, but upon reading the newline Wikipedia article, I noted that recent Apple operating systems (OS X and later) now use the UNIX style \n line ending. As such, my little function may be returning the wrong thing for that case (I don't have a Mac OS on which to test it).

Is there a way I can get Firefox to tell me what the platform-specific newline character is? Perhaps some sort of built-in utility function? I'm using these newlines in the text files my extension writes, and I want to use the platform specific one, so that the files look appropriate across various systems.

Update (2-13-2013): So upon running the navigator.platform.toLowerCase() function call on a Mac-mini (OS X), I get the output value macintel. This would result in my function returning \r instead of \n as it should.

like image 735
Jonah Bishop Avatar asked Feb 08 '13 21:02

Jonah Bishop


2 Answers

Here's what I ended up using:

GetNewLine: function()
{
    var OS = Components.classes["@mozilla.org/xre/app-info;1"].
             getService(Components.interfaces.nsIXULRuntime).OS;

    return /winnt|os2/i.test(OS) ? "\r\n" : /mac/i.test(OS) ? "\r" : "\n";
}

I'm pretty sure the "mac" case should never happen, seeing as it's not listed as a possibility in the OS TARGET variable (which I'm testing via the OS property in nsIXULRuntime).

like image 134
Jonah Bishop Avatar answered Oct 13 '22 00:10

Jonah Bishop


UPDATE 1/16/15: encoding does not handle os specific new line character.

from irc:

07:49   futpib  i guess encoding is for charset only
07:49   Will    character encoding is nothing to do with OS-specific line-endings

If you use OS.File and the TextEncoder it encodes your \n to os appropriate (im pretty sure): https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread

let encoder = new TextEncoder();                                   // This encoder can be reused for several writes
let array = encoder.encode("This is some text");                   // Convert the text to an array
let promise = OS.File.writeAtomic("file.txt", array,               // Write the array atomically to "file.txt", using as temporary
    {tmpPath: "file.txt.tmp"});                                    // buffer "file.txt.tmp".

like image 39
Noitidart Avatar answered Oct 12 '22 23:10

Noitidart