development

경로가 파일인지 디렉토리인지 Node.js 확인

big-blog 2020. 3. 3. 23:05
반응형

경로가 파일인지 디렉토리인지 Node.js 확인


이 작업을 수행하는 방법을 설명하는 검색 결과를 얻지 못하는 것 같습니다.

주어진 경로가 파일인지 디렉토리 (폴더)인지 알 수 있습니다.


fs.lstatSync(path_string).isDirectory()당신에게 말해야합니다. 로부터 문서 :

fs.stat () 및 fs.lstat ()에서 리턴 된 오브젝트는이 유형입니다.

stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()

참고 : 위의 솔루션 것이다 경우; 예를 들어, 또는 존재하지 않습니다. 당신이 원하는 경우 또는 시도 아래 코멘트에 조셉 언급한다.throwErrorfiledirectorytruthyfalsyfs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();


업데이트 : Node.Js> = 10

새로운 fs.promises API를 사용할 수 있습니다

실험적이 기능은 아직 개발 중이며 이후 버전에서 이전 버전과 호환되지 않는 변경 또는 제거 될 수 있습니다. 프로덕션 환경에서는이 기능을 사용하지 않는 것이 좋습니다. 실험 기능은 Node.js 시맨틱 버전 관리 모델의 적용을받지 않습니다.

const fs = require('fs').promises;

(async() => {

        try {
            const stat = await fs.lstat('test.txt');
            console.log(stat.isFile());
        } catch(err) {
            console.error(err);
        }
})();

모든 Node.Js 버전

경로가 파일 또는 디렉토리인지 비동기 적으로 감지하는 방법은 노드에서 권장되는 방법입니다. fs.lstat 사용

const fs = require("fs");

let path = "/path/to/something";

fs.lstat(path, (err, stats) => {

    if(err)
        return console.log(err); //Handle error

    console.log(`Is file: ${stats.isFile()}`);
    console.log(`Is directory: ${stats.isDirectory()}`);
    console.log(`Is symbolic link: ${stats.isSymbolicLink()}`);
    console.log(`Is FIFO: ${stats.isFIFO()}`);
    console.log(`Is socket: ${stats.isSocket()}`);
    console.log(`Is character device: ${stats.isCharacterDevice()}`);
    console.log(`Is block device: ${stats.isBlockDevice()}`);
});

동기식 API를 사용할 때 참고하십시오.

동기식을 사용하면 예외가 즉시 발생합니다. try / catch를 사용하여 예외를 처리하거나 버블 링 할 수 있습니다.

try{
     fs.lstatSync("/some/path").isDirectory()
}catch(e){
   // Handle error
   if(e.code == 'ENOENT'){
     //no such file or directory
     //do something
   }else {
     //do something else
   }
}

진지하게, 질문은 5 년 동안 존재하지만 좋은 외관은 없습니까?

function is_dir(path) {
    try {
        var stat = fs.lstatSync(path);
        return stat.isDirectory();
    } catch (e) {
        // lstatSync throws an error if path doesn't exist
        return false;
    }
}

필요에 따라 노드의 path모듈 에 의존 할 수 있습니다 .

파일 시스템에 도달하지 못할 수도 있습니다 (예 : 파일이 아직 생성되지 않은 경우). 실제로 추가 검증이 필요하지 않은 경우 파일 시스템에 충돌하지 않도록 할 수 있습니다. 확인하려는 내용이 .<extname>형식 을 따르는 것으로 가정 할 수 있다면 이름을 확인하십시오.

분명히 extname이없는 파일을 찾는 경우 파일 시스템을 쳐서 확인해야합니다. 그러나 더 복잡해질 때까지 간단하게 유지하십시오.

const path = require('path');

function isFile(pathItem) {
  return !!path.extname(pathItem);
}

위의 답변은 파일 시스템에 파일 또는 디렉토리 경로가 포함되어 있는지 확인합니다. 그러나 주어진 경로 만 파일 또는 디렉토리인지 식별하지 못합니다.

답은 "/"를 사용하여 디렉토리 기반 경로를 식별하는 것입니다. -> "/ c / dos / run /."과 같이 <-후행.

아직 작성되지 않은 디렉토리 또는 파일의 경로와 같습니다. 또는 다른 컴퓨터의 경로입니다. 또는 동일한 이름의 파일과 디렉토리가 모두 존재하는 경로입니다.

// /tmp/
// |- dozen.path
// |- dozen.path/.
//    |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!

// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
    const isPosix = pathItem.includes("/");
    if ((isPosix && pathItem.endsWith("/")) ||
        (!isPosix && pathItem.endsWith("\\"))) {
        pathItem = pathItem + ".";
    }
    return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
    const isPosix = pathItem.includes("/");
    if (pathItem === "." || pathItem ==- "..") {
        pathItem = (isPosix ? "./" : ".\\") + pathItem;
    }
    return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
} 
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
    if (pathItem === "") {
        return false;
    }
    return !isDirectory(pathItem);
}

노드 버전 : v11.10.0-2019 년 2 월

마지막 생각 : 왜 파일 시스템에 충돌합니까?


다음은 일부 프로그램에서 사용하는 독립형 기능입니다. 이 게시물에서 아무도 사용 promisify하고 await/async기능 하지 않으므로 공유 할 것이라고 생각했습니다.

const isDirectory = async path => {
  try {
    return (await require('util').promisify(require('fs').lstat)(path)).isDirectory()
  } catch (e) {
    return false // or custom the error
  }
}

참고 : 나는 require('fs').promises;1 년 동안 실험을했기 때문에 사용 하지 않고 의존하지 않습니다.

참고 URL : https://stackoverflow.com/questions/15630770/node-js-check-if-path-is-file-or-directory



반응형