Node.js 检查文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17699599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js check if file exists
提问by RomanGorbatko
How do i check the existence of a file?
如何检查文件是否存在?
In the documentation for the module fsthere's a description of the method fs.exists(path, callback). But, as I understand, it checks for the existence of only directories. And I need to check the file!
在模块的文档中fs有方法的描述fs.exists(path, callback)。但是,据我所知,它只检查目录是否存在。我需要检查文件!
How can this be done?
如何才能做到这一点?
回答by dardar.moh
Why not just try opening the file ? fs.open('YourFile', 'a', function (err, fd) { ... })anyway after a minute search try this :
为什么不尝试打开文件?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
}
For Node.js v0.12.x and higher
对于 Node.js v0.12.x 及更高版本
Both path.existsand fs.existshave been deprecated
双方path.exists并fs.exists已弃用
*Edit:
*编辑:
Changed: else if(err.code == 'ENOENT')
更改: else if(err.code == 'ENOENT')
to: else if(err.code === 'ENOENT')
到: else if(err.code === 'ENOENT')
Linter complains about the double equals not being the triple equals.
Linter 抱怨双等号不是三等号。
Using fs.stat:
使用 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);
}
});
回答by Paul Ho
A easier way to do this synchronously.
同步执行此操作的更简单方法。
if (fs.existsSync('/etc/file')) {
console.log('Found file');
}
The API doc says how existsSyncwork:
Test whether or not the given path exists by checking with the file system.
API 文档说明了如何existsSync工作:
通过检查文件系统来测试给定的路径是否存在。
回答by mido
An alternative for stat might be using the new fs.access(...):
stat 的另一种选择可能是使用新的fs.access(...):
minified short promise function for checking:
用于检查的缩小的简短承诺功能:
s => new Promise(r=>fs.access(s, fs.F_OK, e => r(!e)))
Sample usage:
示例用法:
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}′))
expanded Promise way:
扩展Promise方式:
// 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);
});
});
}
or if you wanna do it synchronously:
或者如果你想同步进行:
function checkFileExistsSync(filepath){
let flag = true;
try{
fs.accessSync(filepath, fs.F_OK);
}catch(e){
flag = false;
}
return flag;
}
回答by lmeurs
fs.exists(path, callback)and fs.existsSync(path)are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callbackand https://nodejs.org/api/fs.html#fs_fs_existssync_path.
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。
To test the existence of a file synchronously one can use ie. fs.statSync(path). An fs.Statsobject will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.
要同步测试文件的存在,可以使用 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.");
}
回答by Ignacio Hernández
Old Version before V6: here's the documentation
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');
}
UPDATE
更新
New versions from V6: documentation for fs.stat
V6 的新版本:文档fs.stat
fs.stat('/etc/passwd', function(err, stat) {
if(err == null) {
//Exist
} else if(err.code == 'ENOENT') {
// NO exist
}
});
回答by Дмитрий Васильев
Modern async/await way ( Node 12.8.x )
现代异步/等待方式(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();
We need to use fs.stat() or fs.access()because fs.exists(path, callback)now is deprecated
我们需要使用,fs.stat() or fs.access()因为fs.exists(path, callback)现在已被弃用
Another good way is fs-extra
另一个好方法是fs-extra
回答by Koushik Das
fs.existshas been deprecated since 1.0.0. You can use fs.statinstead of that.
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
}});
Here is the link for the documentation fs.stats
这是文档fs.stats的链接
回答by mikermcneil
@Fox: great answer! Here's a bit of an extension with some more options. It's what I've been using lately as a go-to solution:
@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.'
);
}
P.S. check out fs-extra if you aren't already using it-- it's pretty sweet. https://github.com/jprichardson/node-fs-extra)
PS,如果您还没有使用它,请查看 fs-extra——它非常棒。 https://github.com/jprichardson/node-fs-extra)
回答by chrisw
There are a lot of inaccurate comments about fs.existsSync()being deprecated; it is not.
有很多关于fs.existsSync()被弃用的不准确评论;它不是。
https://nodejs.org/api/fs.html#fs_fs_existssync_path
https://nodejs.org/api/fs.html#fs_fs_existssync_path
Note that fs.exists() is deprecated, but fs.existsSync() is not.
请注意,不推荐使用 fs.exists(),但不推荐使用 fs.existsSync()。
回答by Alexander Zeitler
async/awaitversion using util.promisifyas of Node 8:
async/await使用util.promisify自 Node 8 起的版本:
const fs = require('fs');
const { promisify } = require('util');
const stat = promisify(fs.stat);
describe('async stat', () => {
it('should not throw if file does exist', async () => {
try {
const stats = await stat(path.join('path', 'to', 'existingfile.txt'));
assert.notEqual(stats, null);
} catch (err) {
// shouldn't happen
}
});
});
describe('async stat', () => {
it('should throw if file does not exist', async () => {
try {
const stats = await stat(path.join('path', 'to', 'not', 'existingfile.txt'));
} catch (err) {
assert.notEqual(err, null);
}
});
});

