Node.js檢查路徑是文件還是目錄

本文翻譯自:Node.js check if path is file or directory

I can't seem to get any search results that explain how to do this. 我似乎無法獲得任何解釋如何執行此操作的搜索結果。

All I want to do is be able to know if a given path is a file or a directory (folder). 我想要做的就是能夠知道給定的路徑是文件還是目錄(文件夾)。


#1樓

參考:https://stackoom.com/question/13aHC/Node-js檢查路徑是文件還是目錄


#2樓

fs.lstatSync(path_string).isDirectory() should tell you. fs.lstatSync(path_string).isDirectory()應該告訴你。 From the docs : 來自文檔

Objects returned from fs.stat() and fs.lstat() are of this type. 從fs.stat()和fs.lstat()返回的對象屬於這種類型。

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

NOTE: The above solution will throw an Error if; 注意:如果;上述解決方案將throw Error ; for ex, the file or directory doesn't exist. 例如, filedirectory不存在。 If you want a truthy or falsy try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); 如果你想要一個truthyfalsy嘗試fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); as mentioned by Joseph in the comments below. 正如約瑟夫在下面的評論中提到的那樣。


#3樓

Update: Node.Js >= 10 更新:Node.Js> = 10

We can use the new fs.promises API 我們可以使用新的fs.promises API

Experimental This feature is still under active development and subject to non-backwards compatible changes, or even removal, in any future version. 實驗此功能仍在積極開發中,並且在將來的任何版本中都會受到非向後兼容的更改甚至刪除。 Use of the feature is not recommended in production environments. 建議不要在生產環境中使用該功能。 Experimental features are not subject to the Node.js Semantic Versioning model. 實驗功能不受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);
        }
})();

Any Node.Js version 任何Node.Js版本

Here's how you would detect if a path is a file or a directory asynchronously , which is the recommended approach in node. 以下是如何異步檢測路徑是文件還是目錄的方法,這是節點中推薦的方法。 using fs.lstat 使用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()}`);
});

Note when using the synchronous API: 使用同步API時請注意:

When using the synchronous form any exceptions are immediately thrown. 使用同步表單時,會立即拋出任何異常。 You can use try/catch to handle exceptions or allow them to bubble up. 您可以使用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
   }
}

#4樓

Seriously, question exists five years and no nice facade? 說真的,問題存在五年,沒有好看的外觀?

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

#5樓

The answers above check if a filesystem contains a path that is a file or directory. 上面的答案檢查文件系統是否包含文件或目錄的路徑。 But it doesn't identify if a given path alone is a file or directory. 但它不能識別給定路徑是否僅是文件或目錄。

The answer is to identify directory-based paths using "/." 答案是使用“/”識別基於目錄的路徑。 like --> "/c/dos/run/." 喜歡 - >“/ c / dos / run /。” <-- trailing period. < - 尾隨期。

Like a path of a directory or file that has not been written yet. 就像尚未編寫的目錄或文件的路徑一樣。 Or a path from a different computer. 或者來自不同計算機的路徑。 Or a path where both a file and directory of the same name exists. 或者存在同名文件和目錄的路徑。

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

Node version: v11.10.0 - Feb 2019 節點版本:v11.10.0 - 2019年2月

Last thought: Why even hit the filesystem? 最後想到:爲什麼甚至打到文件系統?


#6樓

Depending on your needs, you can probably rely on node's path module. 根據您的需要,您可以依賴節點的path模塊。

You may not be able to hit the filesystem (eg the file hasn't been created yet) and tbh you probably want to avoid hitting the filesystem unless you really need the extra validation. 您可能無法訪問文件系統(例如,文件尚未創建),並且您可能希望避免命中文件系統,除非您確實需要額外的驗證。 If you can make the assumption that what you are checking for follows .<extname> format, just look at the name. 如果您可以假設您要檢查的內容如下.<extname>格式,請查看名稱。

Obviously if you are looking for a file without an extname you will need to hit the filesystem to be sure. 顯然,如果您正在尋找沒有extname的文件,您需要確保文件系統。 But keep it simple until you need more complicated. 但要保持簡單,直到你需要更復雜。

const path = require('path');

function isFile(pathItem) {
  return !!path.extname(pathItem);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章