Node.js 检查路径是文件还是目录 [英] Node.js check if path is file or directory

查看:24
本文介绍了Node.js 检查路径是文件还是目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

下面应该告诉你.来自文档:

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

注意:

上述解决方案throw一个Error如果;例如,filedirectory 不存在.

如果您想要 truefalse 方法,请尝试 fs.existsSync(dirPath) &&fs.lstatSync(dirPath).isDirectory(); 正如约瑟夫在下面的评论中提到的那样.

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

解决方案

The following should tell you. From the docs:

fs.lstatSync(path_string).isDirectory() 

Objects returned from fs.stat() and fs.lstat() are of this type.

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; for ex, the file or directory doesn't exist.

If you want a true or false approach, try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); as mentioned by Joseph in the comments below.

这篇关于Node.js 检查路径是文件还是目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆