497

我似乎无法获得任何解释如何执行此操作的搜索结果。

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

4

7 回答 7

790

下面应该告诉你。从文档

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

笔记:

上述解决方案throw是一个Errorif;例如,fileordirectory不存在。

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

于 2013-03-26T06:36:58.300 回答
85

更新:Node.Js >= 10

我们可以使用新的fs.promises API

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

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

任何 Node.Js 版本

以下是如何异步检测路径是文件还是目录,这是 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
   }
}
于 2017-04-30T00:42:15.373 回答
30

说真的,问题存在五年而没有漂亮的外观?

function isDir(path) {
    try {
        var stat = fs.lstatSync(path);
        return stat.isDirectory();
    } catch (e) {
        // lstatSync throws an error if path doesn't exist
        return false;
    }
}
于 2018-11-29T00:31:38.113 回答
15

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

您可能无法访问文件系统(例如,尚未创建文件)并且您可能希望避免访问文件系统,除非您确实需要额外的验证。如果您可以假设您正在检查的内容遵循.<extname>格式,只需查看名称即可。

显然,如果您正在寻找一个没有 extname 的文件,您需要点击文件系统来确定。但保持简单,直到你需要更复杂。

const path = require('path');

function isFile(pathItem) {
  return !!path.extname(pathItem);
}
于 2019-03-19T20:57:31.090 回答
2

这是我使用的一个功能。没有人在这篇文章中使用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;
  }
}

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

于 2019-04-04T08:16:01.693 回答
1

如果您在遍历目录时需要这个1

从 Node 10.10+ 开始,fs.readdir具有withFileTypes使其返回目录条目fs.Dirent而不仅仅是文件名的选项。目录条目包含其name有用的方法,例如isDirectoryor isFile,因此您无需fs.lstat显式调用!

你可以像这样使用它:

import { promises as fs } from 'fs';

// ./my-dir has two subdirectories: dir-a, and dir-b
const dirEntries = await fs.readdir('./my-dir', { withFileTypes: true });

// let's filter all directories in ./my-dir
const onlyDirs = dirEntries.filter(de => de.isDirectory()).map(de => de.name);
// onlyDirs is now [ 'dir-a', 'dir-b' ]

1)因为这就是我发现这个问题的方式。

于 2021-12-12T22:00:33.930 回答
0

上面的答案检查文件系统是否包含文件或目录的路径。但它不能确定给定路径是文件还是目录。

答案是使用“/”来识别基于目录的路径。比如 --> "/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 月

最后的想法:为什么还要访问文件系统?

于 2019-02-24T06:20:41.753 回答