[javascript] JavaScript에서 OS 경로 구분 기호를 결정하는 방법은 무엇입니까?

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



답변

Afair는 Windows에서도 항상 경로 구분 기호로 /를 사용할 수 있습니다.

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

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

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

  • 표준 명령 셸 (CMD 또는 COMMAND)은 슬래시를 허용하지 않습니다. 이전 게시물에서 제공된 “cd ./tmp”예제조차도 실패합니다.


답변

path모듈 사용 node.js은 플랫폼 별 파일 구분자 를 반환합니다.

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

편집 : 아래 Sebas의 설명에 따라 이것을 사용하려면 js 파일 상단에 다음을 추가해야합니다.

const path = require('path')


답변

정답

모든 OS는 구분 기호를 전달하는 방법에 관계없이 CD ../ 또는 CD .. \ 또는 CD ..를 허용합니다. 그러나 경로를 다시 읽는 것은 어떻습니까? ‘창’경로가 포함되어 ' '있고 \허용 되는지 어떻게 알 수 있습니까 ?

명백한 ‘Duh!’ 질문

예를 들어 설치 디렉토리에 의존하면 어떻게됩니까 %PROGRAM_FILES% (x86)\Notepad++? 다음 예를 살펴보십시오.

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

어떻게 된 거예요!?

targetDir이 인덱스 사이의 하위 문자열로 설정 0되고 0( indexOf('/')is -1in C:\Program Files\Notepad\Notepad++.exe), 결과적으로 빈 문자열이됩니다.

해결책…

여기에는 다음 게시물의 코드가 포함됩니다. 됩니다. Node.js로 현재 운영 체제를 확인하는 방법

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

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

브라우저 측 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;

구분자를 가져 오는 도우미 함수

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

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

// modifying our getDir method from above...

상위 디렉토리를 가져 오는 도우미 기능 (플랫폼 간)

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() 무엇을 찾고 있는지 알 수있을만큼 똑똑해야합니다.

사용자가 명령 줄 등을 통해 경로를 입력하고 있는지 정말 매끄럽게 확인하고 둘 다 확인할 수 있습니다.

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

이 간단한 작업을 수행하기 위해 모듈을로드하려면 위에서 설명한대로 ‘path’모듈과 path.sep를 사용할 수도 있습니다. 개인적으로 이미 사용 가능한 프로세스의 정보를 확인하는 것으로 충분하다고 생각합니다.

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

그리고 그게 전부입니다!


답변

여기에서 이미 답변했듯이 경로 path.join를 수동으로 구성 하는 데 사용 되는 OS 별 경로 구분 기호를 찾을 수 있습니다 . 그러나 path.join경로 구성을 다룰 때 선호하는 솔루션 인 작업을 수행 할 수도 있습니다 .

예:

const path = require('path');

const directory = 'logs';
const file = 'data.json';

const path1 = `${directory}${path.sep}${file}`;
const path2 = path.join(directory, file);

console.log(path1); // Shows "logs\data.json" on Windows
console.log(path2); // Also shows "logs\data.json" on Windows


답변

“/”를 사용하면 내가 아는 한 모든 OS에서 작동합니다.


답변