本文翻译自:Node.js check if path is file or directory

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). 我想要做的就是能够知道给定的路径是文件还是目录(文件夹)。


#1楼

参考:https://stackoom.com/question/13aHC/Node-js检查路径是文件还是目录


#2楼

fs.lstatSync(path_string).isDirectory() should tell you. fs.lstatSync(path_string).isDirectory()应该告诉你。 From the docs : 来自文档 :

Objects returned from fs.stat() and fs.lstat() are of this type. 从fs.stat()和fs.lstat()返回的对象属于这种类型。

 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; 注意:如果;上述解决方案将throw Error ; for ex, the file or directory doesn't exist. 例如, filedirectory不存在。 If you want a truthy or falsy try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); 如果你想要一个truthyfalsy尝试fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); as mentioned by Joseph in the comments below. 正如约瑟夫在下面的评论中提到的那样。


#3楼

Update: Node.Js >= 10 更新:Node.Js> = 10

We can use the new fs.promises API 我们可以使用新的fs.promises API

Experimental This feature is still under active development and subject to non-backwards compatible changes, or even removal, in any future version. 实验此功能仍在积极开发中,并且在将来的任何版本中都会受到非向后兼容的更改甚至删除。 Use of the feature is not recommended in production environments. 建议不要在生产环境中使用该功能。 Experimental features are not subject to the Node.js Semantic Versioning model. 实验功能不受Node.js语义版本控制模型的约束。

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

Any Node.Js version 任何Node.Js版本

Here's how you would detect if a path is a file or a directory asynchronously , which is the recommended approach in node. 以下是如何异步检测路径是文件还是目录的方法,这是节点中推荐的方法。 using fs.lstat 使用fs.lstat

const fs = require("fs");let path = "/path/to/something";fs.lstat(path, (err, stats) => {if(err)return console.log(err); //Handle errorconsole.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()}`);
});

Note when using the synchronous API: 使用同步API时请注意:

When using the synchronous form any exceptions are immediately thrown. 使用同步表单时,会立即抛出任何异常。 You can use try/catch to handle exceptions or allow them to bubble up. 您可以使用try / catch来处理异常或允许它们冒泡。

try{fs.lstatSync("/some/path").isDirectory()
}catch(e){// Handle errorif(e.code == 'ENOENT'){//no such file or directory//do something}else {//do something else}
}

#4楼

Seriously, question exists five years and no nice facade? 说真的,问题存在五年,没有好看的外观?

function is_dir(path) {try {var stat = fs.lstatSync(path);return stat.isDirectory();} catch (e) {// lstatSync throws an error if path doesn't existreturn false;}
}

#5楼

The answers above check if a filesystem contains a path that is a file or directory. 上面的答案检查文件系统是否包含文件或目录的路径。 But it doesn't identify if a given path alone is a file or directory. 但它不能识别给定路径是否仅是文件或目录。

The answer is to identify directory-based paths using "/." 答案是使用“/”识别基于目录的路径。 like --> "/c/dos/run/." 喜欢 - >“/ c / dos / run /。” <-- trailing period. < - 尾随期。

Like a path of a directory or file that has not been written yet. 就像尚未编写的目录或文件的路径一样。 Or a path from a different computer. 或者来自不同计算机的路径。 Or a path where both a file and directory of the same name exists. 或者存在同名文件和目录的路径。

// /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);
}

Node version: v11.10.0 - Feb 2019 节点版本:v11.10.0 - 2019年2月

Last thought: Why even hit the filesystem? 最后想到:为什么甚至打到文件系统?


#6楼

Depending on your needs, you can probably rely on node's path module. 根据您的需要,您可以依赖节点的path模块。

You may not be able to hit the filesystem (eg the file hasn't been created yet) and tbh you probably want to avoid hitting the filesystem unless you really need the extra validation. 您可能无法访问文件系统(例如,文件尚未创建),并且您可能希望避免命中文件系统,除非您确实需要额外的验证。 If you can make the assumption that what you are checking for follows .<extname> format, just look at the name. 如果您可以假设您要检查的内容如下.<extname>格式,请查看名称。

Obviously if you are looking for a file without an extname you will need to hit the filesystem to be sure. 显然,如果您正在寻找没有extname的文件,您需要确保文件系统。 But keep it simple until you need more complicated. 但要保持简单,直到你需要更复杂。

const path = require('path');function isFile(pathItem) {return !!path.extname(pathItem);
}

Node.js检查路径是文件还是目录相关推荐

  1. 路径,文件,目录,I/O常见操作汇总

    摘要:    文件操作是程序中非常基础和重要的内容,而路径.文件.目录以及I/O都是在进行文件操作时的常见主题,这里想把这些常见的问题作个总结,对于每个问题,尽量提供一些解决方案,即使没有你想要的答案 ...

  2. 使用node.js检查js语法错误

    如果没有一些工具和插件写JavaScript代码遇到语法错误找起来很费时间,请教了同事怎么用node.js检查 用浏览器测试的时候报语法错误. 1.点击红圈中的蓝色按钮,下次刷新是会在抛出异常的时候自 ...

  3. 极简 Node.js 入门 - 3.2 文件读取

    Node.js 提供了多种读取文件的 API fs.readFile fs.readFile(path[, options], callback) 是最常用的读取文件方法,用于异步读取文件的全部内容 ...

  4. Node.js 得到当前目录下文件修改文件名

    博客园第一篇,平时都用 .net ,现在 node.js 比较火,就用它做一些小工具,比较方便 Node.js 得到当前目录下文件修改文件名,把 .txt 修改为.md var fs = requir ...

  5. Node.js复制/删除服务器端文件到指定目录文件夹下,并且预判是否存在该目录,如果没有,则递归创建该文件夹目录

    注意,前情提示: 本代码基于<Node.js(nodejs)对本地JSON文件进行增.删.改.查操作(轻车熟路)> 传送门Node.js(nodejs)对本地JSON文件进行增.删.改.查 ...

  6. js 删除服务器文件,Node.js复制/删除服务器端文件到指定目录文件夹下,并且预判是否存在该目录,如果没有,则递归创建该文件夹目录...

    注意,前情提示: 本代码基于<Node.js(nodejs)对本地JSON文件进行增.删.改.查操作(轻车熟路)> 传送门https://blog.csdn.net/qq_37860634 ...

  7. Node.js文件系统模块——读写文件操作

    文章目录 前言 一.导入fs模块 1.readFile() && readFileSync() 2.writeFile() && writeFileSync() 3.a ...

  8. 使用node.js+express+multer实现文件的上传

    经过一次又一次的失败和一起又一次的崩溃放弃.很多的bug总是出现在那些最细小的不容易察觉到的环节.搜百度一般很难找到解决办法,这时候我们通过Stackoverflow.Google等搜索才是真的大腿. ...

  9. Node.js API参考文档(目录)

    Node.js v11.5.0 API参考文档 Node.js®是基于Chrome的V8 JavaScript引擎构建的JavaScript运行时. 关于文档 用法和示例 断言测试 稳定性:2 - 稳 ...

最新文章

  1. 2011.8.2号面试
  2. 13、Power Query-逆透视列的解析(上)
  3. 【面试必备】GET和POST两种基本请求方法的区别
  4. session 和cookie的理解
  5. linux之如何在任意目录执行我常用的脚本文件
  6. Lost HTML Intellisense within ASP.NET AJAX Controls
  7. 团队项目——测量小助手个人一周详细计划表
  8. python实现括号分组
  9. mysql xp系统时间_【Mysql5.5 XP系统下载】mysql XP系统安装图解
  10. android转iOS看什么书,一起聊聊:是什么让你从Android转向iOS?
  11. Android时代的赢创之路
  12. STM32串口通讯——中断方式
  13. 用opencv在图片上面添加水印
  14. h3c s5820交换机_简单配置
  15. BZOJ4987:Tree(树形DP)
  16. 翻译图片中文字的网站
  17. ABAP 设置鼠标光标
  18. 【技术邻】基于有限元方法的整车风噪仿真分析
  19. SPH算法的理论和实践(1)
  20. 工欲善其事必先利其器 之 DockerDesktop(下)

热门文章

  1. write combining
  2. 计算机什么是符号健,在电脑健盘上怎么打:符号
  3. 更新下来的vue项目如何跑起来
  4. 简单的数据库连接测试方法
  5. OSChina 周日乱弹 ——书中自有颜如玉
  6. 用Python画一个“中国福”,送给想要祝福的人吧
  7. pwm调速流程图小车_循迹+pwm调速的小车源程序
  8. java hevc和heif_关于 iOS 和 macOS 的 HEVC 和 HEIF
  9. 个人永久性免费-Excel催化剂功能第21波-Excel与Sqlserver零门槛交互-执行SQL语句篇...
  10. 微型计算机机安装硬盘教程,装机DIY之硬盘安装方法 不同硬盘安装方法图解教程...