我似乎找不到任何解释如何做到这一点的搜索结果。
所有我想做的是能够知道一个给定的路径是一个文件还是一个目录(文件夹)。
我似乎找不到任何解释如何做到这一点的搜索结果。
所有我想做的是能够知道一个给定的路径是一个文件还是一个目录(文件夹)。
当前回答
说真的,问题是存在了五年,却没有好的表象?
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;
}
}
其他回答
如果你在遍历一个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)因为我就是这样发现这个问题的。
上面的答案检查文件系统是否包含文件或目录的路径。但它不能识别给定的路径单独是文件还是目录。
答案是使用“/.”来识别基于目录的路径,比如——>“/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月
最后一个想法:为什么要攻击文件系统?
我可以检查一个目录或文件是否存在:
// 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;
返回类型的函数
我喜欢咖啡
type: (uri)-> (fina) ->
fs.lstat uri, (erro,stats) ->
console.log {erro} if erro
fina(
stats.isDirectory() and "directory" or
stats.isFile() and "document" or
stats.isSymbolicLink() and "link" or
stats.isSocket() and "socket" or
stats.isBlockDevice() and "block" or
stats.isCharacterDevice() and "character" or
stats.isFIFO() and "fifo"
)
用法:
dozo.type("<path>") (type) ->
console.log "type is #{type}"
说真的,问题是存在了五年,却没有好的表象?
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;
}
}