我似乎找不到任何解释如何做到这一点的搜索结果。
我想要做的就是能够知道给定的路径是文件还是目录(文件夹)。
我似乎找不到任何解释如何做到这一点的搜索结果。
我想要做的就是能够知道给定的路径是文件还是目录(文件夹)。
以下内容应该能告诉你。来自文档:
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()
上面的解决方案在文件或目录不存在时将抛出
Error
。
如果您想采用true
或false
方式,请尝试下面评论中Joseph提到的fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
方法。
let isDirExists = fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
这行代码的功能是检查指定路径是否存在,并判断该路径是否为目录。如果路径存在且为目录,则变量isDirExists将被设置为true。需要注意的是,这行代码使用了Node.js提供的fs模块来操作文件系统。其中,existsSync方法用于检查路径是否存在,而lstatSync方法则用于获取路径的状态信息,包括路径是否为目录。 - Jossef Harush Kadourifs.lstat()
?文档中说它总是false
:如果<fs.Stats>
对象是通过fs.lstat()
获得的,那么这个方法[<fs.Stats>.isDirectory()
]将始终返回false
。 这是因为fs.lstat()
返回有关符号链接本身而不是其解析路径的信息。 - snickle我们可以使用新的fs.promises API。
const fs = require('fs').promises;
(async() => {
const stat = await fs.lstat('test.txt');
console.log(stat.isFile());
})().catch(console.error)
以下是您如何异步检测路径是否为文件或目录的方法,这是在Node中推荐的方法。使用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
}
}
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;
}
}
/tmp/
时,出现 [Error: EACCES: permission denied, scandir '/tmp/snap.skype']
的错误。 - Marinos An如果你需要在遍历目录时使用这个功能(因为我是这样发现这个问题的):
自 Node 10.10+ 版本起,fs.readdir
提供了一个 withFileTypes
选项,使其返回目录条目的 fs.Dirent
对象而不是字符串。目录对象具有 name
属性和有用的方法,如 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' ]
根据您的需求,您可以在node的path
模块上进行依赖。
您可能无法访问文件系统(例如,文件尚未创建),并且您可能希望避免访问文件系统,除非您确实需要额外的验证。如果您可以假设所检查的内容遵循.<extname>
格式,请只查看名称。
显然,如果您正在寻找没有扩展名的文件,您需要访问文件系统以确保其存在。但在需要更复杂操作之前,请保持简单。
const path = require('path');
function isFile(pathItem) {
return !!path.extname(pathItem);
}
promisify
和await/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;
,因为它已经实验了一年,最好不要依赖它。// /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月
最后的想法:为什么要访问文件系统?
.git
或myFolder.txt
,该怎么办? - wow ow// 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}"
scandir()
返回的Dirent
和stat()
返回的Stat
都有isFile()
和isDirectory()
方法,但前者不会跟随符号链接,而后者会跟随。 - hippietrail