Node.js 检查路径是文件还是目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15630770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:00:35  来源:igfitidea点击:

Node.js check if path is file or directory

node.jspathdirectoryfilesystemsfs

提问by ThomasReggi

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).

我想要做的就是能够知道给定的路径是文件还是目录(文件夹)。

回答by Jason Sperske

fs.lstatSync(path_string).isDirectory()should tell you. From the docs:

fs.lstatSync(path_string).isDirectory()应该告诉你。从文档

Objects returned from fs.stat() and fs.lstat() are of this type.

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

从 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 solutionwill throwan Errorif; for ex, the fileor directorydoesn't exist.

上述溶液throw一个ErrorIF; 例如,filedirectory不存在。

If you want a trueor falseapproach, try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();as mentioned by Joseph in the comments below.

如果您想要一个truefalse方法,请尝试fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();按照约瑟夫在下面的评论中提到的方法。

回答by Marcos Casagrande

Update: Node.Js >= 10

更新:Node.Js >= 10

We can use the new fs.promisesAPI

我们可以使用新的fs.promisesAPI

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

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


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

以下是异步检测路径是文件还是目录的方法,这是 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()}`);
});


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

回答by lama12345

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

回答by cndw

Depending on your needs, you can probably rely on node's pathmodule.

根据您的需要,您可能可以依赖节点的path模块。

You may not be able to hit the filesystem (e.g. 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. But keep it simple until you need more complicated.

显然,如果您要查找没有 extname 的文件,则需要点击文件系统才能确定。但保持简单,直到你需要更复杂的。

const path = require('path');

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

回答by vdegenne

Here's a function that I use. Nobody is making use of promisifyand await/asyncfeature in this post so I thought I would share.

这是我使用的一个函数。没有人正在使用promisifyawait/async功能在这个岗位,所以我想我也有同感。

const promisify = require('util').promisify;
const lstat = promisify(require('fs').lstat);

async function isDirectory (path) {
  try {
    return (await lstat(path)).isDirectory();
  }
  catch (e) {
    return false;
  }
}

Note : I don't use require('fs').promises;because it has been experimental for one year now, better not rely on it.

注意:我不使用,require('fs').promises;因为它已经实验了一年,最好不要依赖它。

回答by TamusJRoyce

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/." <-- trailing period.

答案是使用“/”标识基于目录的路径。像 --> "/c/dos/run/." <-- 尾随期。

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?

最后一个想法:为什么还要攻击文件系统?