¿Cómo determinar el separador de ruta del sistema operativo en JavaScript?


¿Cómo puedo saber en JavaScript qué separador de ruta se utiliza en el sistema operativo donde se ejecuta el script?

Author: VVS, 2008-09-24

5 answers

Siempre puede usar / como separador de ruta, incluso en Windows.

Cita de http://bytes.com/forum/thread23123.html:

Entonces, la situación se puede resumir más bien simplemente:

  • Todos los servicios de DOS desde DOS 2.0 y todas las API de Windows aceptan reenviar barra o barra invertida. Siempre lo he hecho.

  • Ninguno de los shells de comandos estándar (CMD o COMANDO) aceptará reenviar recortar. Incluso el "cd ./tmp" ejemplo dado en un post anterior falla.

 16
Author: VVS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-24 07:32:01

Uso path module in node.js devuelve el separador de archivos específico de la plataforma.
ejemplo

path.sep  // on *nix evaluates to a string equal to "/"
 68
Author: t98907,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-05 19:05:38

La respuesta de VVS es correcta, con la excepción de analizar una ruta dada por un archivo de entrada en Internet explorer (probado con IE8 - no sé acerca de otras versiones). En este caso, la ruta dada por el valor del elemento input (input.valor) está en la forma "C:\fakepath\". Observe las barras invertidas aquí.

 4
Author: Milagre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-01 03:49:15

La Respuesta Correcta

Yes todos los sistemas operativos aceptan CD ../ o CD ..\ o CD .. independientemente de cómo pase en separadores. Pero qué hay de leer un camino de regreso. ¿Cómo sabrías si es decir, una ruta de' windows', con ' ' y \ permitido.

El Obvio ' Duh! Pregunta

Qué sucede cuando se depende, por ejemplo, del directorio de instalación %PROGRAM_FILES% (x86)\Notepad++. Tomemos el siguiente ejemplo.

var fs = require('fs');                             // file system module
var targetDir = 'C:\Program Files (x86)\Notepad++'; // target installer dir

// read all files in the directory
fs.readdir(targetDir, function(err, files) {

    if(!err){
        for(var i = 0; i < files.length; ++i){
            var currFile = files[i];

            console.log(currFile); 
            // ex output: 'C:\Program Files (x86)\Notepad++\notepad++.exe'

            // attempt to print the parent directory of currFile
            var fileDir = getDir(currFile);

            console.log(fileDir);  
            // output is empty string, ''...what!?
        }
    }
});

function getDir(filePath){
    if(filePath !== '' && filePath != null){

       // this will fail on Windows, and work on Others
       return filePath.substring(0, filePath.lastIndexOf('/') + 1);
    }
}

¡Qué pasó!?

targetDir se está configurando a un subcadena entre los índices 0, y 0 (indexOf('/') is -1 in C:\Program Files\Notepad\Notepad++.exe), resultando en la cadena vacía.

La Solución...

Esto incluye el código del siguiente post: Cómo determino el sistema operativo actual con Node.js

myGlobals = { isWin: false, isOsX:false, isNix:false };

Detección del sistema operativo del lado del servidor.

// this var could likely a global or available to all parts of your app
if(/^win/.test(process.platform))     { myGlobals.isWin=true; }
else if(process.platform === 'darwin'){ myGlobals.isOsX=true; }
else if(process.platform === 'linux') { myGlobals.isNix=true; }

Detección del lado del navegador del sistema operativo

var appVer = navigator.appVersion;
if      (appVer.indexOf("Win")!=-1)   myGlobals.isWin = true;
else if (appVer.indexOf("Mac")!=-1)   myGlobals.isOsX = true;
else if (appVer.indexOf("X11")!=-1)   myGlobals.isNix = true;
else if (appVer.indexOf("Linux")!=-1) myGlobals.isNix = true;

Función auxiliar para obtener el separador

function getPathSeparator(){
    if(myGlobals.isWin){
        return '\\';
    }
    else if(myGlobals.isOsx  || myGlobals.isNix){
        return '/';
    }

    // default to *nix system.
    return '/';
}

// modifying our getDir method from above...

Función auxiliar para obtener el directorio padre (cruz plataforma)

function getDir(filePath){
    if(filePath !== '' && filePath != null){
       // this will fail on Windows, and work on Others
       return filePath.substring(0, filePath.lastIndexOf(getPathSeparator()) + 1);
    }
}

getDir() debe ser lo suficientemente inteligente para saber que su busca.

Usted puede conseguir incluso realmente slick y comprobar para ambos si el usuario está introduciendo una ruta a través de la línea de comandos, etc.

// in the body of getDir() ...
var sepIndex = filePath.lastIndexOf('/');
if(sepIndex == -1){
    sepIndex = filePath.lastIndexOf('\\');
}

// include the trailing separator
return filePath.substring(0, sepIndex+1);

También puede usar el módulo 'path' y path.sep como se indicó anteriormente, si desea cargar un módulo para hacer esto simple de una tarea. Personalmente, creo que basta con comprobar la información del proceso que ya está disponible para usted.

var path = require('path');
var fileSep = path.sep;    // returns '\\' on windows, '/' on *nix

Y Eso es ¡Todos!

 2
Author: Decoded,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:59

Simplemente use "/", funciona en todos los sistemas operativos que yo sepa.

 0
Author: Vincent McNabb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-24 07:25:46