我如何检查文件的存在?
在该模块的文档中,fs有一个方法的描述fs.exists(path, callback).但是,据我所知,它检查是否只存在目录.我需要检查文件!
如何才能做到这一点?
Fox*_*Fox 215
为什么不尝试打开文件?fs.open('YourFile', 'a', function (err, fd) { ... })
无论如何,一分钟搜索后试试这个:
var path = require('path');
path.exists('foo.txt', function(exists) {
if (exists) {
// do something
}
});
// or
if (path.existsSync('foo.txt')) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
对于Node.js v0.12.x及更高版本
双方path.exists并fs.exists已弃用
*编辑:
更改: else if(err.code == 'ENOENT')
至: else if(err.code === 'ENOENT')
Linter抱怨双重等于不等于三等于.
使用fs.stat:
fs.stat('foo.txt', function(err, stat) {
if(err == null) {
console.log('File exists');
} else if(err.code === 'ENOENT') {
// file does not exist
fs.writeFile('log.txt', 'Some log\n');
} else {
console.log('Some other error: ', err.code);
}
});
Run Code Online (Sandbox Code Playgroud)
Pau*_* Ho 47
同步执行此操作的更简单方法.
if (fs.existsSync('/etc/file')) {
console.log('Found file');
}
Run Code Online (Sandbox Code Playgroud)
API文档说明existsSync工作原理:
通过检查文件系统来测试给定路径是否存在.
mid*_*ido 39
stat的替代方案可能是使用新的fs.access(...):
缩小的短期承诺函数用于检查:
s => new Promise(r=>fs.access(s, fs.F_OK, e => r(!e)))
Run Code Online (Sandbox Code Playgroud)
样品用法:
let checkFileExists = s => new Promise(r=>fs.access(s, fs.F_OK, e => r(!e)))
checkFileExists("Some File Location")
.then(bool => console.log(´file exists: ${bool}´))
Run Code Online (Sandbox Code Playgroud)
扩展承诺方式:
// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
return new Promise((resolve, reject) => {
fs.access(filepath, fs.F_OK, error => {
resolve(!error);
});
});
}
Run Code Online (Sandbox Code Playgroud)
或者如果你想同步这样做:
function checkFileExistsSync(filepath){
let flag = true;
try{
fs.accessSync(filepath, fs.F_OK);
}catch(e){
flag = false;
}
return flag;
}
Run Code Online (Sandbox Code Playgroud)
Дми*_*ьев 23
现代异步/等待方式(Node 12.8.x)
const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));
const main = async () => {
console.log(await fileExists('/path/myfile.txt'));
}
main();
Run Code Online (Sandbox Code Playgroud)
我们需要使用,fs.stat() or fs.access()因为fs.exists(path, callback)现在已被弃用
另一个好方法是fs-extra
Man*_*ddy 19
2021 年 8 月
阅读完所有帖子后:
let filePath = "./directory1/file1.txt";
if (fs.existsSync(filePath)) {
console.log("The file exists");
} else {
console.log("The file does not exist");
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*lin 19
异步等待风格的简洁解决方案:
import { stat } from 'fs/promises';
const exists = await stat('foo.txt')
.then(() => true)
.catch(() => false);
Run Code Online (Sandbox Code Playgroud)
lme*_*urs 18
fs.exists(path, callback)而fs.existsSync(path)现在已过时,见https://nodejs.org/api/fs.html#fs_fs_exists_path_callback和https://nodejs.org/api/fs.html#fs_fs_existssync_path.
为了同步测试文件的存在,可以使用ie.fs.statSync(path).fs.Stats如果文件存在,将返回一个对象,请参阅https://nodejs.org/api/fs.html#fs_class_fs_stats,否则将引发错误,该错误将被try/catch语句捕获.
var fs = require('fs'),
path = '/path/to/my/file',
stats;
try {
stats = fs.statSync(path);
console.log("File exists.");
}
catch (e) {
console.log("File does not exist.");
}
Run Code Online (Sandbox Code Playgroud)
Ign*_*dez 12
V6之前的旧版本: 这是文档
const fs = require('fs');
fs.exists('/etc/passwd', (exists) => {
console.log(exists ? 'it\'s there' : 'no passwd!');
});
// or Sync
if (fs.existsSync('/etc/passwd')) {
console.log('it\'s there');
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
V6的新版本:文档fs.stat
fs.stat('/etc/passwd', function(err, stat) {
if(err == null) {
//Exist
} else if(err.code == 'ENOENT') {
// NO exist
}
});
Run Code Online (Sandbox Code Playgroud)
fs.exists自1.0.0以来已被弃用.你可以用fs.stat而不是那个.
var fs = require('fs');
fs.stat(path, (err, stats) => {
if ( !stats.isFile(filename) ) { // do this
}
else { // do this
}});
Run Code Online (Sandbox Code Playgroud)
这是fs.stats文档的链接
@Fox:很棒的答案!这里有一些扩展,有更多选项.这是我最近一直在使用的首选解决方案:
var fs = require('fs');
fs.lstat( targetPath, function (err, inodeStatus) {
if (err) {
// file does not exist-
if (err.code === 'ENOENT' ) {
console.log('No file or directory at',targetPath);
return;
}
// miscellaneous error (e.g. permissions)
console.error(err);
return;
}
// Check if this is a file or directory
var isDirectory = inodeStatus.isDirectory();
// Get file size
//
// NOTE: this won't work recursively for directories-- see:
// http://stackoverflow.com/a/7550430/486547
//
var sizeInBytes = inodeStatus.size;
console.log(
(isDirectory ? 'Folder' : 'File'),
'at',targetPath,
'is',sizeInBytes,'bytes.'
);
}
Run Code Online (Sandbox Code Playgroud)
PS如果你还没有使用它,请查看fs-extra--非常好. https://github.com/jprichardson/node-fs-extra)
关于fs.existsSync()不推荐使用的评论有很多不正确;它不是。
https://nodejs.org/api/fs.html#fs_fs_existssync_path
请注意,不建议使用fs.exists(),但不建议使用fs.existsSync()。
| 归档时间: |
|
| 查看次数: |
193842 次 |
| 最近记录: |