문제

스크립트가 실행되는 OS에서 어떤 경로 분리기가 사용되는지 JavaScript에서 어떻게 알 수 있습니까?

도움이 되었습니까?

해결책

afair 당신은 항상 창에서도 경로 분리기로 사용할 수 있습니다.

인용 http://bytes.com/forum/thread23123.html:

따라서 상황은 간단하게 요약 될 수 있습니다.

  • DOS 2.0 및 모든 Windows API 이후의 모든 DOS 서비스는 전진 슬래시 또는 백 슬래시를 허용합니다. 항상 가지고 있습니다.

  • 표준 명령 쉘 (CMD 또는 명령) 중 어느 것도 전방 슬래시를 수락하지 않습니다. 이전 게시물에 주어진 "cd ./tmp"예제조차 실패합니다.

다른 팁

Use path module in node.js returns the platform-specific file separator.
example

path.sep  // on *nix evaluates to a string equal to "/"

Edit: As per Sebas's comment below, to use this, you need to add this at the top of your js file:

const path = require('path')

The Correct Answer

Yes all OS's accept CD ../ or CD ..\ or CD .. regardless of how you pass in separators. But what about reading a path back. How would you know if its say, a 'windows' path, with ' ' and \ allowed.

The Obvious 'Duh!' Question

What happens when you depend on, for example, the installation directory %PROGRAM_FILES% (x86)\Notepad++. Take the following example.

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);
    }
}

What happened!?

targetDir is being set to a substring between the indices 0, and 0 (indexOf('/') is -1 in C:\Program Files\Notepad\Notepad++.exe), resulting in the empty string.

The Solution...

This includes code from the following post: How do I determine the current operating system with Node.js

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

Server side detection of OS.

// 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; }

Browser side detection of OS

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;

Helper Function to get the separator

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

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

// modifying our getDir method from above...

Helper function to get the parent directory (cross platform)

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() must be intelligent enough to know which its looking for.

You can get even really slick and check for both if the user is inputting a path via command line, 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);

You can also use 'path' module and path.sep as stated above, if you want to load a module to do this simple of a task. Personally, i think it sufficient to just check the information from the process that is already available to you.

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

And Thats All Folks!

VVS's answer is correct, with the exception of parsing a path given by a file input in internet explorer (tested with IE8 - I do not know about other versions). In this case, the path given by the input element's value (input.value) is in the form "C:\fakepath\<filename>". Note the backslashes here.

Just use "/", it works on all OS's as far as I know.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top