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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值