如何使用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);
}
其他回答
我使用下面的函数来测试文件是否存在。它还捕捉到其他例外。因此,如果存在权限问题,例如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'
}
fs.exists()已弃用,请勿使用https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
您可以使用以下方式实现核心nodejs:https://github.com/nodejs/node-v0.x-archive/blob/master/lib/module.js#L86
function statPath(path) {
try {
return fs.statSync(path);
} catch (ex) {}
return false;
}
这将返回stats对象,然后在获得stats对象后,您可以尝试
var exist = statPath('/path/to/your/file.js');
if(exist && exist.isFile()) {
// do something
}
使用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);
});
});
为那些“正确”指出它不能直接回答问题的人更新了asnwer,更多的是带来了一个替代选项。
同步解决方案:
fs.existsSync('filePath')也可以在此处查看文档。
如果路径存在,则返回true,否则返回false。
Async Promise解决方案
在异步上下文中,您可以使用await关键字编写异步版本同步方法。您可以简单地将异步回调方法转换为如下承诺:
function fileExists(path){
return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK,
(err, result) => err ? fail(err) : resolve(result))
//F_OK checks if file is visible, is default does no need to be specified.
}
async function doSomething() {
var exists = await fileExists('filePath');
if(exists){
console.log('file exists');
}
}
access()上的文档。
查看源代码,有一个同步版本的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
推荐文章
- 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代理