我似乎找不到任何解释如何做到这一点的搜索结果。
所有我想做的是能够知道一个给定的路径是一个文件还是一个目录(文件夹)。
我似乎找不到任何解释如何做到这一点的搜索结果。
所有我想做的是能够知道一个给定的路径是一个文件还是一个目录(文件夹)。
当前回答
下面的内容会告诉你。从文档中可以看出:
fs.lstatSync(path_string).isDirectory()
从fs.stat()和fs.lstat()返回的对象就是这种类型。 stats.isFile () stats.isDirectory () stats.isBlockDevice () stats.isCharacterDevice () stats.isSymbolicLink() //(只对fs.lstat()有效) stats.isFIFO () stats.isSocket ()
注意:
上述解决方案将抛出一个错误,如果;对于ex,文件或目录不存在。
如果你想要一个真或假的方法,尝试fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();正如约瑟夫在下面的评论中提到的。
其他回答
我可以检查一个目录或文件是否存在:
// This returns if the file is not a directory.
if(fs.lstatSync(dir).isDirectory() == false) return;
// This returns if the folder is not a file.
if(fs.lstatSync(dir).isFile() == false) return;
上面的答案检查文件系统是否包含文件或目录的路径。但它不能识别给定的路径单独是文件还是目录。
答案是使用“/.”来识别基于目录的路径,比如——>“/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月
最后一个想法:为什么要攻击文件系统?
说真的,问题是存在了五年,却没有好的表象?
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;
}
}
根据您的需要,您可能依赖于node的path模块。
您可能无法访问文件系统(例如,文件还没有创建),tbh您可能希望避免访问文件系统,除非您确实需要额外的验证。如果您可以假设要检查的内容如下。<extname>格式,那么只需查看名称即可。
显然,如果您正在寻找一个没有extname的文件,您将需要访问文件系统以确定。但是要保持简单,直到你需要更复杂的。
const path = require('path');
function isFile(pathItem) {
return !!path.extname(pathItem);
}
如果你在遍历一个directory1时需要这个
自节点10.10+,fs。readdir有withFileTypes选项,使其返回目录项fs。Dirent而不是filename。目录条目包含它的名称和有用的方法,如isDirectory或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)因为我就是这样发现这个问题的。