如何使用node.js同步检查文件或目录是否存在?
当前回答
使用fileSystem(fs)测试将触发错误对象,然后需要将其包装在try/catch语句中。节省一些精力,使用0.4.x分支中介绍的功能。
var path = require('path');
var dirs = ['one', 'two', 'three'];
dirs.map(function(dir) {
path.exists(dir, function(exists) {
var message = (exists) ? dir + ': is a directory' : dir + ': is not a directory';
console.log(message);
});
});
其他回答
我使用下面的函数来测试文件是否存在。它还捕捉到其他例外。因此,如果存在权限问题,例如chmod ugo rwx文件名或在Windows中右键单击->财产->安全->高级->权限条目:空列表。。函数应返回异常。该文件存在,但我们无权访问它。忽略此类异常是错误的。
function fileExists(path) {
try {
return fs.statSync(path).isFile();
}
catch (e) {
if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
console.log("File does not exist.");
return false;
}
console.log("Exception fs.statSync (" + path + "): " + e);
throw e; // something else went wrong, we don't have rights, ...
}
}
异常输出,nodejs错误文档,以防文件不存在:
{
[Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'X:\\delsdfsdf.txt'
}
如果我们没有该文件的权限,但存在,则出现异常:
{
[Error: EPERM: operation not permitted, stat 'X:\file.txt']
errno: -4048,
code: 'EPERM',
syscall: 'stat',
path: 'X:\\file.txt'
}
const fs = require('fs');
检查以下功能,
if(fs.existsSync(<path_that_need_to_be_checked>)){
// enter the code to excecute after the folder is there.
}
else{
// Below code to create the folder, if its not there
fs.mkdir('<folder_name>', cb function);
}
使用当前推荐的(截至2015年)API(根据节点文档),我会这样做:
var fs = require('fs');
function fileExists(filePath)
{
try
{
return fs.statSync(filePath).isFile();
}
catch (err)
{
return false;
}
}
针对@broadband在评论中提出的EPERM问题,这提出了一个很好的观点。在很多情况下,fileExists()可能不是一个很好的方法来考虑这一点,因为fileExistes()不能真正承诺布尔返回。您可能能够确定文件是否存在,但也可能会出现权限错误。权限错误并不一定意味着该文件存在,因为您可能对包含要检查的文件的目录缺少权限。当然,在检查文件是否存在时,也有可能遇到其他错误。
因此,我上面的代码实际上是doesFileExistAndDoIHaveAccessToIt(),但您的问题可能是doesFileNotExistAndCouldICreateIt(),这将是完全不同的逻辑(需要考虑EPERM错误等)。
虽然fs.existsSync的答案直接解决了这里提出的问题,但这通常不是您想要的(您不只是想知道路径上是否存在“某物”,您可能关心存在的“某物”是文件还是目录)。
底线是,如果您正在检查文件是否存在,那么您这样做可能是因为您打算根据结果采取一些操作,并且逻辑(检查和/或后续操作)应该考虑到在该路径中找到的东西可能是文件或目录,并且在检查过程中可能会遇到EPERM或其他错误。
查看源代码,有一个同步版本的path.exists-path.existsSync。看起来文档中没有找到它。
更新:
path.exists和path.existsSync现在已弃用。请使用fs.exists和fs.existsSync。
2016年更新:
fs.exists和fs.existsSync也已被弃用。请改用fs.stat()或fs.access()。
2019年更新:
使用fs.existsSync。它没有被弃用。https://nodejs.org/api/fs.html#fs_fs_existssync_path
使用fileSystem(fs)测试将触发错误对象,然后需要将其包装在try/catch语句中。节省一些精力,使用0.4.x分支中介绍的功能。
var path = require('path');
var dirs = ['one', 'two', 'three'];
dirs.map(function(dir) {
path.exists(dir, function(exists) {
var message = (exists) ? dir + ': is a directory' : dir + ': is not a directory';
console.log(message);
});
});
推荐文章
- ReferenceError: description没有定义NodeJs
- 将一个二进制的NodeJS Buffer转换为JavaScript的ArrayBuffer
- AngularJS只适用于单页应用程序吗?
- 如何在vue-cli项目中更改端口号
- 同步和异步编程(在node.js中)的区别是什么?
- 如何编辑通过npm安装的节点模块?
- “node_modules”文件夹应该包含在git存储库中吗
- 使用package.json在全局和本地安装依赖项
- this.libOptions.parse不是一个函数
- 对嵌套文件夹运行npm install的最好方法是什么?
- 节点Multer异常字段
- 很好的初学者教程socket.io?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理