如何使用node.js同步检查文件或目录是否存在?
当前回答
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);
}
其他回答
另一个更新
我自己需要这个问题的答案,我查阅了节点文档,似乎您不应该使用fs.exists,而是使用fs.open并使用输出的错误来检测文件是否不存在:
从文档中:
fs.exists()是一个时代错误,只因历史原因而存在。在您自己的代码中使用它几乎没有任何理由。特别是,在打开文件之前检查文件是否存在让你容易受到种族状况影响的反模式:另一种进程可能会在调用fs.exists()和fs.open()。只需打开文件并在不存在时处理错误那里
http://nodejs.org/api/fs.html#fs_fs_exists_path_callback
这里有一个简单的包装解决方案:
var fs = require('fs')
function getFileRealPath(s){
try {return fs.realpathSync(s);} catch(e){return false;}
}
用法:
适用于目录和文件如果项存在,则返回文件或目录的路径如果项不存在,则返回false
例子:
var realPath,pathToCheck='<your_dir_or_file>'
if( (realPath=getFileRealPath(pathToCheck)) === false){
console.log('file/dir not found: '+pathToCheck);
} else {
console.log('file/dir exists: '+realPath);
}
确保使用==运算符测试return是否等于false。在适当的工作条件下,fs.realpathSync()返回false是没有逻辑原因的,所以我认为这应该可以100%工作。
我更希望看到一个不会产生错误和性能影响的解决方案。从API的角度来看,fs.exists()似乎是最优雅的解决方案。
使用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);
});
});
查看源代码,有一个同步版本的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
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);
}
推荐文章
- 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代理